Method Name in log4net C#

后端 未结 2 1390
忘了有多久
忘了有多久 2021-02-10 14:56

I created a c# wrapper for log4net.

It has Debug() and Error() methods.

I want to log the method name which logs the record, but If I try to use the %method conv

2条回答
  •  别那么骄傲
    2021-02-10 15:15

    If you really must use a wrapper class, then the best way is to get the calling method in the wrapper and then store that as a property:

    var stackFrames = new StackTrace().GetFrames();
    var callingframe = stackFrames.ElementAt(1);
    var method = callingframe .GetMethod().Name;
    
    // Store in log4net ThreadContext:
    ThreadContext.Properties["method"] = method;
    

    Then in the layout reference the property:

    
    

    There is also a way to resolve this just using the layout, you would use %stacktrace in your layout to get the call stack, specifically %stacktrace{2} to get the calling method.

    Note that when you use this, the whole stack is logged, including the wrapper method.

    Example output:

    log4net.Tests.Stacktrace_Tests.StackTrace_In_PatternLayout > log4net.Tests.Wrapper.Debug

提交回复
热议问题