开发者

Avoid getting logger instance in each class I want to log with

How do I avoid calling GetLogger on every class I want to use logging? I'd rather prefer some static class with static property, which initializes correct logger instance based on callers class type.

开发者_C百科Current configuration

Currently i have log4net config file, which is loaded with every assembly I need logging in. From AssemblyInfo.cs:

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

Then in my class i have a ILog Log variable which i initialize.

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

But I would rather like

Logging.Log.Error(errorStr);


You can add a static LogManager class and delegate the responsibility to it for Creation. Then it can hold a reference to the ILog and you can use it as you want.

This is how my class looks:

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);
    }
}


Usually a Singleton design pattern is used in such cases, and you would send it the type of

the other classes just like some Java libraries deal with logging.

You have to use reflection to determine the type of the caller class, I mean the one which called it by:

Logging.Log.Error(errorStr);

Hope that helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜