I'd like to change the name of my log at runtime without changing the appender. Basically, once it gets to a certain set time of day I'd like to be able to use a different file.
This is what my appender looks like:
<appender name="info" type="log4net.Appender.RollingFileAppender">
<file value="logs\" />
<datePattern value="yyyyMMdd'_INFO.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline[%date]-%level-%logger[%M]- Linea:%L - %message%newline"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="INFO"/>
<param name="LevelMax" value="INFO"/>
</filter>
</appender>
This is the function where I iterate through the appenders:
public void SetLogFile(string fileName)
{
foreach (var appender in log.Logger.Repository.GetAppenders())
{
try
{
((log4net.Appender.FileAppender)appender).File = fileName;
((log4net.Appender.FileAppender)appender).ActivateOptions();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
SetLogFile("log1.txt");
Which creates the following file for this specific example:
log1.txt20171221_INFO.log
I'd like for my log file to be named log1.txt
and not have the datePattern
set in the log4net.config
file concatenated with the name, but I can't figure out how to do it without changing the log4net.config
appender configuration.
As you are using RollFileAppender, you have to change the RollingStyle and set the path accordingly.
foreach (var appender in log.Logger.Repository.GetAppenders())
{
try
{
string file = Path.GetDirectoryName(((log4net.Appender.RollingFileAppender)appender).File);
string filename = Path.Combine(file, fileName);
switch (((log4net.Appender.RollingFileAppender)appender).RollingStyle)
{
case log4net.Appender.RollingFileAppender.RollingMode.Date:
((log4net.Appender.RollingFileAppender)appender).RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Once;
break;
case log4net.Appender.RollingFileAppender.RollingMode.Composite:
((log4net.Appender.RollingFileAppender)appender).RollingStyle = log4net.Appender.RollingFileAppender.RollingMode.Size;
break;
}
((log4net.Appender.FileAppender)appender).File = filename;
((log4net.Appender.FileAppender)appender).ActivateOptions();
}
catch (Exception ex) {}
}