Configuring log4net appenders via XML file *and* c

2019-02-27 06:25发布

I started to play with log4net today and so far, I really like it. In order to preserve our current logging functionality, the app needs to create a new log file whenever the application is started. The log file name has the date and time stamp encoded in it. Currently, I've got log4net configured via an XmlConfigurator, which works great, except that the filename for my RollingFileAppender is hardcoded in the configuration XML file.

I'd like to continue to use the XmlConfigurator, but after calling Configure(), I want to get at the RollingFileAppender and, in code, change its file value to be a dynamically-generated string. The sample documentation online seems to be down right now, but I've poked through the SDK reference, and it looks like I could use the Heirarchy and GetAppenders() to do what I need to do. Am I on the right track?

Ok, I took a stab at this and tried the following code, which didn't work:

private static readonly ILog _log = LogManager.GetLogger(typeof(GUI));
// in the config file, I've set the filename to example.log, and it works
XmlConfigurator.Configure(new FileInfo("log_config.xml"));
Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
if(hierarchy != null) {
    // get the appenders
    IAppender[] appenders = hierarchy.GetAppenders();
    // change the filename for the RollingFileAppender
    foreach( IAppender a in appenders) {
        RollingFileAppender rfa = a as RollingFileAppender;
        if(rfa == null)
            continue;
        rfa.File = "newfile.log"; // no runtime error, but doesn't work.
    }
}
_log.Info("Application started");

2条回答
唯我独甜
2楼-- · 2019-02-27 06:42

Do you in this case need the rolling file appender? If not I would expect that your code would create the desired result if you used the normal file appender.

Edit: Maybe it works with the RollingFile Appender if you call ActivateOptions() on the appender.

查看更多
老娘就宠你
3楼-- · 2019-02-27 06:47

Try this snippet:

XmlConfigurator.Configure();

log4net.Repository.ILoggerRepository repo = LogManager.GetRepository();
foreach (log4net.Appender.IAppender appender in repo.GetAppenders())
{
if (appender.Name.CompareTo("RollingFileAppender") == 0 && appender is log4net.Appender.RollingFileAppender)
{
   var appndr = appender as log4net.Appender.RollingFileAppender;
   string logPath = "MyApplication.log";
   appndr.File = logPath;
   appndr.ActivateOptions();
}

I had posted similar article here

查看更多
登录 后发表回答