通过XML文件*和*代码配置log4net附加程序 [英] Configuring log4net appenders via XML file *and* code

查看:98
本文介绍了通过XML文件*和*代码配置log4net附加程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天开始玩log4net,到目前为止,我真的很喜欢.为了保留我们当前的日志记录功能,无论何时启动应用程序,应用程序都需要创建一个新的日志文件.日志文件名中已编码日期和时间戳.目前,我已经通过XmlConfigurator配置了log4net,该方法非常有效,除了RollingFileAppender的文件名硬编码在配置XML文件中.

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.

我想继续使用XmlConfigurator,但是在调用Configure()之后,我想使用RollingFileAppender,并在代码中将其文件值更改为动态生成的字符串.样本在线文档现在似乎已关闭,但我仔细阅读了SDK参考,看起来我可以使用HeirarchyGetAppenders()来完成我需要做的事情.我在正确的轨道上吗?

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");

推荐答案

在这种情况下,您是否需要滚动文件附加程序?如果不是这样,我希望如果您使用普通的文件附加程序,您的代码将产生所需的结果.

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.

如果您在附加程序上调用ActivateOptions(),也许它可以与RollingFile Appender一起使用.

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

这篇关于通过XML文件*和*代码配置log4net附加程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆