Change the log file name several times at run time

Can I change the log file name for the file adapter while the application is running? This will be done several times / day.

I will try to dwell on my own: the application writes the firmware to the device. All devices that the user has already worked with are in the grid. The user can start a new recording wizard or resume or restart an action on an already running device. What I would like to do is keep a log of all the steps the user takes for a particular device.

For example: when the user is working on the device AB0124, I want to write to the log file AB0124.log. When he finishes working on this device and starts working on the XY5618 device, I want to register these actions in XY5618.log

I read that you can use a context property ( here and here and many other messages), but you must set the property before creating the registrar. Thus, instead of creating a registrar in a class, I create it in my method after setting the property. But still nothing is being recorded.

When I set the file name hardcoded in config, it works. Did I miss something here?

Log4Net.config:

<appender name="StepsLogAppender" type="log4net.Appender.FileAppender"> <filter type="log4net.Filter.LevelMatchFilter"> <levelToMatch value="INFO"/> </filter> <filter type="log4net.Filter.DenyAllFilter" /> <file type="log4net.Util.PatternString" value="%property{LogPathModifier}" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date{dd/MM/yyyy - HH:mm:ss} - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="StepsLogAppender" /> </root> 

WITH#

 public void WriteStepInfo(string device, int step) { log4net.ThreadContext.Properties["LogPathModifier"] = string.Format("D:\\StepsDevice_{0}.txt", device); var log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Info(string.Format("Device {0} - step {1}.", device, step)); } 

And in AssemblyInfo.cs:

 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] 
+6
source share
2 answers

Peter's answer led me in the right direction, but I ended up doing this in code instead of editing and saving the configuration file.

 public void WriteStepInfo(string device, int step) { var h = (log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository(); foreach (IAppender a in h.Root.Appenders) { if (a.Name == "StepsLogAppender") { FileAppender fa = (FileAppender)a; var logFileLocation = string.Format(".\\Logs\\Device_{0}.log", device); fa.File = logFileLocation; fa.ActivateOptions(); break; } } Log.Info(string.Format("Device {0} - step {1}. Different file for each device", device, step)); } 
+7
source

You can open the log4net.config file from your application and change the name. Then save the file (log4net.config) and the log file will be modified.

+1
source

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


All Articles