开发者

Log4net - optimal strategy when using inheritance

开发者 https://www.devze.com 2023-01-21 02:36 出处:网络
I have integrated log4net in my app. I have a few helper methods to assist in logging which call log4net. When refactoring, I plan to move these methods to base class so that the code is not repeated

I have integrated log4net in my app. I have a few helper methods to assist in logging which call log4net. When refactoring, I plan to move these methods to base class so that the code is not repeated in other derived classes.

Without the inheritance model, following worked correctly in each class

private static readonly ILog Log = LogManager.GetLogge开发者_开发知识库r(MethodBase.GetCurrentMethod().DeclaringType);

Placing the above in the base class will return the declaring type as base class and not derived class.

What is an optimal way to move this declaration to the base class?

At present, I can think of a few ways to achieve this but don't find them optimal.


I think I would do this:

LogManager.GetLogger(this.GetType());


Based on Sefan's answer here's how I declared it in the base class

/// <summary>
    /// This is delay loaded to allow us to capture the class type of the inherited class on request
    /// </summary>
    private ILog log = null;

    protected ILog Log
    {
        get
        {
            if (log == null)
            {
                log = LogManager.GetLogger(this.GetType());
            }

            return log;
        }
    }


We just redeclare it in each class that needs a logger (the point of it being a private static) and use a code snippet to make that as simple as typing log<tab><tab> if you wanted to get extra fancy though you could do something like:

public class Loggable<T> where T : Loggable<T>
{
    private static readonly ILog log = LogManager.GetLogger(typeof(T));

    protected static ILog Log
    {
        get
        {
            return log;
        }
    }
}

And punch T through your inheritance hierarchy so that it is the most derived class. The problem with all of the answers here is that you lose information about where log messages are coming from, so I would personally stick to your original code despite the added boilerplate.

0

精彩评论

暂无评论...
验证码 换一张
取 消