Reputation: 1600
I have a configuration file for my project that includes the configuration for the log4net logger. It is as it follows:
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="MyLogFile.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value ="Start file processing..."/>
<conversionPattern value="%newline%date - %message%exception" />
<footer type="log4net.Util.PatternString" value="File processing finished.%newline%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
I am wondering if it is possible dynamicaly to change the value of my :
<file value="MyLogFile.txt" />
Upvotes: 4
Views: 4173
Reputation: 2893
You can do some thing like this also
<file type="log4net.Util.PatternString" value="%property{LogFileName}.log" />
ILog logger = LogManager.GetLogger("SampleAppender");
log4net.GlobalContext.Properties["LogFileName"] = "MyLog";
XmlConfigurator.Configure();
Upvotes: 0
Reputation: 236228
Simplest way to dynamically change log4net configuration, is setting xml configurator to watch changes of config file:
[assembly: XmlConfigurator(Watch = true)]
When you will do some changes to application config file (one which lives near exe) log4net will automatically reconfigure itself and further output will go to other file.
If you for some reason want to do this programatically then you need to get instance of file appender from logger repository (aka Hierarchy):
var fileAppender = LogManager.GetLoggerRepository()
.GetAppenders()
.OfType<FileAppender>()
.FirstOrDefault(fa => fa.Name == "LogFileAppender");
And change it's settings:
if (fileAppender != null)
{
fileAppender.File = Path.Combine(Environment.CurrentDirectory, "foo.txt");
fileAppender.ActivateOptions();
}
Keep in mind, that simple setting File
property will not open new file - it just sets file name which should be opened during appender activation. So, you need to activate it manually just after changing file path.
Upvotes: 2
Reputation: 60498
Yup, you can access the appender at runtime and change the properties of it. Just make sure you call ActivateOptions
after changing anything.
Here's an example that changes the connection string for an ADO appender. You should be able to adapt that easily enough for what you are trying to do:
http://blog.gfader.com/2010/05/log4net-how-to-change-settings-of.html
Upvotes: 1
Reputation: 27944
You can read the log4net file, parse it with a xml parser in your application and change the file value attribute. Then save the log4net file. If you have watch=true, the new configuration will be picked up as the new configuration.
Upvotes: 0