Is it possible to change the name of a logfile for a fileappender while the application is running? It will be done a few times / day.
I'll try to elaborate myself a bit more: my app writes firmware on a device. All the devices the user already worked on, are in a grid. The user can start a new writing-wizard or can resume or restart the action on an already started device. What I would like to do is keep a log of all the steps performed by the user for a certain device.
For example: when the user works on device AB0124, I want to write to a logfile called AB0124.log. When he ends working on that device and starts on device XY5618 I want to log those actions in XY5618.log
I've read that it's possible to use a context-property (here and here and a lot of other posts), but you have to set the property before creating the logger. So, instead of creating a logger in the class, I create one in my method after setting the property. But so far, nothing gets logged.
When I set the filename hardcoded in the config, it's working. Am I missing somehting 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>
C#:
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 the AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
The answer of Peter brought me in the right direction, but I ended up doing it in code instead of editing and saving the config-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));
}
You can open the log4net.config file from your application and change the name. Then save the file (log4net.config) and the logging file will be changed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With