Using NLog is there any way to log the name of the logger before the trailing dot?

logging, nlog

Solution

I would suggest writing a custom wrapper LayoutRenderer, something like this:

using NLog.Config;
using NLog.LayoutRenderers;

namespace NLog.LayoutRenderers.Wrappers
{
    [LayoutRenderer("loggerprefix")]
    [ThreadAgnostic]
    public sealed class LoggerPrefixRendererWrapper : WrapperLayoutRendererBase
    {
        protected override string Transform(string text)
        {
            return text.Substring(0,text.LastIndexOf('.'));
        }
    }
}

The idea is that you would apply this wrapper to the `logger` LayoutRenderer like this:

${loggerprefix:${logger}}

The Transform method should receive the full name of logger (fully qualified class name in the case that you are using classnames as logger names). Inside Transform, simply return the contents of "text" (i.e. the logger name) up to, but not including, the last `'.'`.

You will also have to add a reference to the assembly in the NLog config.

  <extensions>
    <add assembly="MyAssembly"/>
  </extensions>

I based this on the WrapperLayoutRenderers you can find in the NLog repository.

Good luck!

Problem

I have a scenario where I could reduce the number of targets in a configuration file if I could log the name of the logger before the trailing dot character. Using `${logger:shortName=true}` it is possible to render the short name of the logger, that is by definition the part after the trailing dot character. However what I want to log is the part before the dot character. For example I might use a logger name of `MyNamespace.MyClass`, using `${logger:shortName=true}` I would get a value of `MyClass` but I cannot see a way to get a value of just `MyNamespace` as using `${logger:shortName=false}` returns the full name of `MyNamespace.MyClass`. So I would like to know if this is possible?

Original source