简体   繁体   中英

Intercepting log messages in nlog

We have a need to intercept the entries that nlog is writing to disk so that any URLs/IP addresses and similar security-sensitive information can be obfuscated or somehow encoded.

For example, if any URL that is logged it should be converted from http://servername:2212/webservice to (http)://servername/2212/webservice

Is there any nlog pattern that would take a regex and convert to another string?

or is it possible to intercept the writing of the log file to achieve this?

Any help, suggestion or redirection would be really helpful.

We are using .NET 4.5, nlog 4.4, C#

Write a wrapper layoutrenderer, you can wrap than all the layout renderers. . eg if you had the layout ${message}${exception} , it will be

${intercept:inner=${message}${exception}} 

code:

[LayoutRenderer("intercept")]
public sealed class InterceptLayoutRendererWrapper : WrapperLayoutRendererBase
{

    /// <summary>
    /// Option you could set from config or code
    /// </summary>
    [DefaultValue(true)]
    public bool Option1 { get; set; }


    /// <summary>
    /// Renders the inner layout contents.

    /// OR override TransformFormattedMesssage, and change the stringbuilder (less string allocations)
    /// </summary>
    /// <param name="logEvent">The log event.</param>
    /// <returns>Contents of inner layout.</returns>
    protected override string RenderInner(LogEventInfo logEvent)
    {
        var text = this.Inner.Render(logEvent);
        return interceptSomething(text);
    }

}

and register:

LayoutRenderer.Register<InterceptLayoutRendererWrapper>("intercept"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM