Log4net - 使用继承时的最佳策略

byt*_*yte 11 c# log4net

我已经在我的应用程序中集成了log4net.我有一些辅助方法来帮助记录调用log4net.在重构时,我计划将这些方法移动到基类,以便代码不会在其他派生类中重复.

没有继承模型,以下在每个类中都能正常工作

private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Run Code Online (Sandbox Code Playgroud)

将上面的内容放在基类中将返回声明类型作为基类而不是派生类.

将此声明移动到基类的最佳方法是什么?

目前,我可以想到几种方法来实现这一目标,但却找不到最佳方法.

Ste*_*gli 11

我想我会这样做:

LogManager.GetLogger(this.GetType());
Run Code Online (Sandbox Code Playgroud)


bas*_*rat 5

基于 Sefan 的回答,这是我在基类中声明它的方式

/// <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;
        }
    }
Run Code Online (Sandbox Code Playgroud)