Can NLog preserve callsite information through c# extension methods?

后端 未结 3 742
南方客
南方客 2021-01-27 19:37

EDIT: While similar, this is not the same as the questions about using an NLog wrapper. Extension methods add another level of indirection which makes even a proper wra

3条回答
  •  生来不讨喜
    2021-01-27 20:06

    EDIT: Unfortunately, this answer no longer works. NLog broke this functionality in 3.2.0 and it looks like they don't plan to fix it: https://github.com/NLog/NLog/issues/696.

    I found a workaround. While not identical to the solution for just an NLog wrapper, it turns out to be similar.

    Instead of having the ILogger implementer (the NLog wrapper) simply pass it's own type to NLog, I created an overload that allowed passing it a type from the caller:

    public void Log( LogEntry entry )
    {
        this.Log( this.GetType(), entry );
    }
    
    public void Log( Type type, LogEntry entry)
    {
        NLogLogger.Log( type, new NLog.LogEventInfo( ... ) );
    }
    

    This requires adding the overload to interface, which makes it sort of ugly (and NLog specific):

    public interface ILogger
    {
        void Log( LogEntry entry );
        void Log( Type type, LogEntry entry );
    }
    

    And then the extension methods can be modified:

    public static class LoggerExtensions
    {
        public static void Debug( this ILogger logger, string format params object[] args )
        {
            logger.Log( typeof(LoggerExtensions), LogLevel.Debug, format, args ) );
        }
    
        ...
    }
    

    While not as clean as simply using a wrapper, this does allow the use of extension methods while retaining callsite information. If anyone has a cleaner way I'd like to see it.

提交回复
热议问题