无法正确配置log4net

时间:2016-06-04 13:15:07

标签: c# log4net

我尝试通过代码配置log4net但是当我将其用作Logger.Info("new bar");时出现以下错误:

  

在C:\ Users \ Documents \ NinjaTrader 7 \ bin \ Custom \ Indicator \ STSVer1.cs中的NinjaTrader.Indicator.Logger.Info(Object msg):第610行   在NinjaTrader.Indicator.STSVer1.OnBarUpdate()中的c:\ Users \ Documents \ NinjaTrader 7 \ bin \ Custom \ Indicator \ STSVer1.cs:第108行
  对象引用未设置为对象的实例。

public static class Logger
{
    private static log4net.ILog Log { get; set; }

    static Logger()
    { 
        Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
        hierarchy.Root.RemoveAllAppenders(); /*Remove any other appenders*/

        FileAppender fileAppender = new FileAppender();
        fileAppender.AppendToFile = true;
        fileAppender.LockingModel = new FileAppender.MinimalLock();
        fileAppender.File = @"c:\temp\logevents.txt";
        PatternLayout pl = new PatternLayout();
        pl.ConversionPattern = "%d [%2%t] %-5p [%-10c]   %m%n%n";
        pl.ActivateOptions();
        fileAppender.Layout = pl;
        fileAppender.ActivateOptions();

        log4net.Config.BasicConfigurator.Configure(fileAppender);
        //Test logger
        ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


    //      Log = log4net.LogManager.GetLogger(typeof(Logger));
    }

    public static void Error(object msg)
    {
        Log.Error(msg);
    }

    public static void Error(object msg, Exception ex)
    {
        Log.Error(msg, ex);
    }

    public static void Error(Exception ex)
    {
        Log.Error(ex.Message, ex);
    }

    public static void Info(object msg)
    {
        Log.Info(msg);
    }
}

1 个答案:

答案 0 :(得分:2)

Logger - 类静态构造函数中,您不必初始化属性Log,而是初始化名为Log的局部变量。因此,当您从Log方法中调用时,null属性为Info

从代码的以下行中删除类型名称ILog

ILog Log =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
顺便说一下,你注释掉的下面一行是正确的 - 关于正确初始化属性。