Search code examples
c#log4netlog4net-configurationlog4net-appender

Log4net configuration file path from a key in app.config


I have a created a custom log component class library which uses log4net. I want to have the log4net configuration file path to be read from a key in app.config. so app.config will have a key "log4netconfigpath" and this key will contain path of configuration file. So how I load log4net configuration from a key in app.config.

Currently I read config from a fixed path like below.

[assembly: log4net.Config.XmlConfigurator(ConfigFile=@"log4netconfig.config", Watch=true)]

Solution

  • I think you use the below code while initializing your application,

    var logPath = Convert.ToString(ConfigurationManager.AppSettings["log4netconfigpath"])
    log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(path));
    

    But if you are using this in the Console or Winservice app and adding the log config file inside the project then please get the basePath and then append the path

    string path = System.AppDomain.CurrentDomain.BaseDirectory;
    log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(path + logPath)));
    

    Namespace : System.Configuration