C # Log4Net - dynamically change log directory programmatically

I read most of the related topics regarding programmatically changing the log directory, but the answers were a bit complicated.

My problem is trying to dynamically change the save location of my log file from a C # application. I have a text box with a browse button to choose where it should be saved.

Does anyone have an idea or can you point me in the right direction with some kind of code? I tried to play with similar ideas, but I canโ€™t understand that this is correct.

+5
source share
2 answers

If you want your log file to be located in a specific place that will be determined at runtime, maybe your project output directory, then you can configure your entry in the .config file this way

file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" 

and then in the code, before calling log4net configure, set a new path as shown below

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\file1"; //log file path log4net.Config.XmlConfigurator.Configure(); 

So, if your requirement changes the log directory so often, then update the property value each time followed by .Configure() .

+12
source

Although the Asked Question is pretty old, but I accidentally find a really good solution here that worked for me.

 public static bool ChangeLogFileName(string appenderName, string newFilename) { var rootRepository = log4net.LogManager.GetRepository(); foreach (var appender in rootRepository.GetAppenders()) { if (appender.Name.Equals(appenderName) && appender is log4net.Appender.FileAppender) { var fileAppender = appender as log4net.Appender.FileAppender; fileAppender.File = newFilename; fileAppender.ActivateOptions(); return true; // Appender found and name changed to NewFilename } } return false; // appender not found } 
0
source

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


All Articles