1

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#

gorkem
  • 731
  • 1
  • 10
  • 17
kgpai
  • 15
  • 4

1 Answers1

1

Write a wrapper layoutrenderer, you can wrap than all the layout renderers. . e.g. 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"); 
Rolf Kristensen
  • 17,785
  • 1
  • 51
  • 70
Julian
  • 33,915
  • 22
  • 119
  • 174
  • Alternative one could make render-wrapper that uses the Transform method to "fix" the log-text. The render-wrapper would have a list of regex-expressions for matching text-patterns in the log-text, and when match then replace with a standard-string. Similar to https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/Wrappers/Rot13LayoutRendererWrapper.cs https://github.com/NLog/NLog/wiki/Rot13-Layout-Renderer – Rolf Kristensen May 18 '17 at 19:31
  • And a custom target wrapper is also an option - it wraps the full target. But a bit less flexible. – Julian May 18 '17 at 19:32