log4net set from an external config file not working

前端 未结 2 1119
失恋的感觉
失恋的感觉 2020-12-21 05:09

I\'m having a weird issue with log4net.

In an ASP.NET application, I want to configure log4net externally, so I have a separate log4net.config file which I hook up t

相关标签:
2条回答
  • 2020-12-21 05:16

    Tell the application to configure log4net using external config file. There are really two spots for this. First, the global.asax and second the assemblyInfo.cs file. Note, that most of the time you will start out with a global.asax file with all of the code inline. For whatever reason, the only way I could get this to work was to break the global.asax up to use a code-behind and then ass the assemblyInfo.cs file. So it ends up looking like this.

    global.asax:
    
    <%@ Application Language="C#" Inherits="GlobalAsax" %>
    
    global.asax.cs (in your App_Code folder):
    
    using System;
    using System.Web;
    
    public class GlobalAsax : HttpApplication
    {
        // you may have lots of other code here
        void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
        }
    }
    

    Now that you have your application calling log4net's configuration, you can set an attribute in your assembly info so that log4net knows where to look for the configuration file.

    AssemblyInfo.cs (in your App_Code folder):
    
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
    

    The watch flag tells log4net to keep an eye on the configuration file for potential changes. This is helpful if you want to change the configuration from logging everthing to errors only during the middle of your testing.

    Then, start logging.

    0 讨论(0)
  • 2020-12-21 05:32

    To sum up what Bibhu has said. It has all to do with log4net.Config.XmlConfigurator.

    You have to configure log4net before logging will start. So whenever you use your LogManager class the hosting application (windows, web) must configure the logging.

    Either that or you need to do it in your LogManager.

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