How to set dynamic save path in log4net configuration file

I have a configuration file for my project that includes a configuration for log4net logger. This is as 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 to dynamically change the value of my:

 <file value="MyLogFile.txt" /> 
+4
source share
4 answers

The simplest way to dynamically change the log4net configuration is to install the xml configurator to view changes to the configuration file:

 [assembly: XmlConfigurator(Watch = true)] 

When you make some changes to the application configuration file (the one that lives next to exe), log4net will automatically reconfigure itself, and further output will go to another file.


If for some reason you want to do this programmatically, you need to get an instance of the file application from the log repository (aka Hierarchy):

 var fileAppender = LogManager.GetLoggerRepository() .GetAppenders() .OfType<FileAppender>() .FirstOrDefault(fa => fa.Name == "LogFileAppender"); 

And change the settings:

 if (fileAppender != null) { fileAppender.File = Path.Combine(Environment.CurrentDirectory, "foo.txt"); fileAppender.ActivateOptions(); } 

Remember that this simple File property does not open a new file - it simply sets the name of the file that should be opened during appender activation. So, you need to activate it manually right after changing the file path.

+2
source

Yup, you can access the application at runtime and change its properties. Just make sure you call ActivateOptions after changing something.

Here is an example that modifies the connection string for the ADO appender. You should be able to adapt this easily enough for what you are trying to do:

http://blog.gfader.com/2010/05/log4net-how-to-change-settings-of.html

+1
source

You can read the log4net file, parse it with the xml parser in the application, and change the file value attribute. Then save the log4net file. If you have watch = true, the new configuration will be selected as the new configuration.

0
source

You can also do something like this

 <file type="log4net.Util.PatternString" value="%property{LogFileName}.log" /> ILog logger = LogManager.GetLogger("SampleAppender"); log4net.GlobalContext.Properties["LogFileName"] = "MyLog"; XmlConfigurator.Configure(); 
0
source

Source: https://habr.com/ru/post/1495456/