Can NLog preserve callsite information through c# extension methods?

后端 未结 3 782
南方客
南方客 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:10

    Late to the party but I had issue with this solution given that I use extension methods for my wrapper. By passing the assembly to LogManager I was able to get NLog to ignore my extension class.

        /// 
        /// Bootstrap the wrapper class
        /// 
        static Logger()
        {
            LogManager.AddHiddenAssembly(typeof(LoggingExtensions).Assembly);
        }
    

    There isn't much detail from the docs other than

    Adds the given assembly which will be skipped when NLog is trying to find the calling method on stack trace.

    from NLog Documentation

    With this setup, I've even managed to get extension methods + DI working with SimpleInjector.

    To show you can still have a callsite within the same assembly using this method

    My Logger() lives in a Utilities project along with a SettingsHelper() I setup a test with output from SettingsHelper:

    2015-08-18 20:44:07.5352 | vstest.executionengine.x86 | Debug | Utilities.Settings.SettingsHelper | A test from the same assembly as Logger() | ActionTests.LoggingTest+LogTest.RunLogTest

    The bold bit is the ${callsite}

    My SettingsHelper() test:

    ILogger logger = new Logger(typeof(SettingsHelper));
    logger.Debug("A test from the same assembly as Logger()");
    

    Don't forget also to use the overload that takes LogEventInfo()

    _logger.Log(typeof(Logger), logEvent);
    

提交回复
热议问题