Configuring log4net applications via XML file * and * code
I started playing with log4net today and still, I really like it. To preserve our current logging functionality, each time the application starts, the application must create a new log file. The log file name has a date / time stamp encoded in it. I currently have log4net configured with XmlConfigurator
, which works great, except that the filename for mine is RollingFileAppender
hardcoded in the config config file.
I would keep using XmlConfigurator
, but after the call, Configure()
I want to get RollingFileAppender
and, in code, change its file value as a dynamically generated string. The sample documentation online doesn't seem to be working right now, but I poked through the SDK link and it looks like I could use Heirarchy
and GetAppenders()
do what I need. Am I on the right track?
Ok I took a hit on 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");
a source to share
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 posted a similar article here
a source to share