开发者

Configuring log4net appenders via XML file *and* code

开发者 https://www.devze.com 2022-12-29 16:38 出处:网络
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

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 co开发者_Go百科de, 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");


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号