Unable to filter on class name (in NLog.config) when using anotar catel nlog logging

StackOverflow https://stackoverflow.com/questions/21351404

  •  02-10-2022
  •  | 
  •  

Pregunta

I am using anotar catel fody for logging in my application.

In NLog.config I want to use different levels for certain classes. Example config

<logger name="SpaceA.*"
        minlevel="Info"
        writeTo="file"
        final="true" />
<logger name="*"
        minlevel="Debug"
        writeTo="file" />

I have created a NLogListener class which derives from catel's LogListenerBase.

public class NLogListener : LogListenerBase
{
    private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();

    protected override void Debug(ILog log, string message, object extraData)
    {
        Log.Debug(message);
    }

    protected override void Info(ILog log, string message, object extraData)
    {
        Log.Info(message);
    }

    protected override void Warning(ILog log, string message, object extraData)
    {
        Log.Warn(message);
    }

    protected override void Error(ILog log, string message, object extraData)
    {
        Log.Error(message);
    }
    #endregion Methods
}

In my code I use Catel Anotar Fody:

LogTo.Debug("Starting something...");

Now no matter where I use the logging, it is all being displayed as coming from the namespace where I have defined the LogListerer.

What am I doing wrong and ergo do I have to change to be able to filter the NLog on class names like it normally should?

¿Fue útil?

Solución

The problem is that you get the current class logger in the LogListener:

private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();

That way, you always log to the NLogListener type. What you should do is get the right logger type for each entry:

protected override void Debug(ILog log, string message, object extraData)
{
    var nlog = NLog.LogManager.GetClassLogger(log.TargetType);
    nlog.Debug(message);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top