避免在我想要记录的每个类中获取记录器实例

时间:2011-01-24 11:23:56

标签: c# logging log4net global-variables

如何避免在我想要使用日志记录的每个类上调用GetLogger?我宁愿选择一些带静态属性的静态类,它根据调用者类类型初始化正确的logger实例。

当前配置

目前我有log4net配置文件,它载有我需要登录的每个程序集。来自AssemblyInfo.cs:

[assembly: log4net.Config.XmlConfigurator(
    ConfigFile = xx.SharePoint.xxConfiguration.Log4NetConfigFilePath,
    Watch = true)]

然后在我班上我有一个ILog Log变量,我初始化。

ILog log = log4net.LogManager.GetLogger(this.GetType());
...
Log.Error(errorStr);

但我更喜欢

Logging.Log.Error(errorStr);

2 个答案:

答案 0 :(得分:0)

通常在这种情况下使用Singleton设计模式,并且您将发送

类型

其他类就像一些Java库处理日志记录一样。

你必须使用反射来确定调用者类的类型,我的意思是调用它的那个:

Logging.Log.Error(errorStr);

希望有所帮助。

答案 1 :(得分:0)

您可以添加一个静态LogManager类,并将其责任委派给Creation。然后它可以保存对ILog的引用,您可以根据需要使用它。

这是我班级的样子:

public static class LogManager
{
    public static readonly ILogger Log = CreateLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    /// <summary>
    /// Creates the logger for the specified type.
    /// </summary>
    /// <param name="loggerType">Type of the logger.</param>
    /// <returns></returns>
    public static Logger CreateLogger(Type loggerType)
    {
        return new Logger(loggerType);
    }

    /// <summary>
    /// Creates the logger for the specified name.
    /// </summary>
    /// <param name="loggerName">Name of the logger.</param>
    /// <returns></returns>
    public static Logger CreateLogger(string loggerName)
    {
        return new Logger(loggerName);
    }
}
相关问题