When using wrapper, how to preserve class and method name for Log4Net to log?

前端 未结 3 1452
野的像风
野的像风 2020-11-28 16:37

I need a Log4net wrapper - to be exposed to a number of different components in a large app. I obviously want to retain the class and method name when logging but I would ke

3条回答
  •  一生所求
    2020-11-28 17:12

    Log4net allows you to access method name for instance like this %method. This is not the fastest operation but if you need to debug something you may very well use it. I believe your question is about the fact that log4net will not output the correct method name if you use a wrapper.

    To solve that problem you have to look at how log4net wrote the ILog implementation. This is basically a wrapper around the internal log4net Logger and therefore the very same problem applies to the ILog implementation, too. I did basically the following:

    // define a field such as this
    private static readonly Type ThisDeclaringType = typeof(MyLogWrapper);
    
    // in constructor. Note: I use the internal Logger!
    this.Logger = LogManager.GetLogger(name).Logger;
    
    // I created a WriteLog method that calls the internal logger like this
    // you will need to translate to the internal log levels
    // message and ex are the items I want to log (ex can be null)
    this.Logger.Log(MyLogWrapper.ThisDeclaringType, log4netLevel, message, ex);
    

    Obviously there are some things to do yet, but the important points are mentioned.

提交回复
热议问题