Method Name in log4net C#

后端 未结 2 528
星月不相逢
星月不相逢 2021-02-10 14:51

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:30

    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

提交回复
热议问题