Enable file logging for log4net from code instead of from configuration

前端 未结 3 1732
误落风尘
误落风尘 2020-12-01 11:12

Why in the world does the following test fail? (its in xunit) I\'ve tried it with different appenders and it never writes anything though the log seems like it is ready to

相关标签:
3条回答
  • 2020-12-01 11:28

    Just throwing a guess out there...

    Do you have the XmlConfiguration defined in your assembly?

    Did you forget it in your test project?

    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
    

    That usually burns me every once in a while.

    0 讨论(0)
  • 2020-12-01 11:37

    I always use the code below to configure log4net from code. Works great!

    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 = Server.MapPath("/") + "log.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.Debug("Testing!");
    
    0 讨论(0)
  • 2020-12-01 11:41

    Still can't say why the above code doesn't work but I got log4net to configure properly and use my appender by replacing all the configuration code with:

    log4net.Config.BasicConfigurator.Configure(_appender);
    

    From here.

    0 讨论(0)
提交回复
热议问题