Reputation: 355
I have implemented log4net
in my windows service and it works as expected and created new file with current date as per config setting.
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="Logs\log-%utcdate{yyyy-MM-dd}.txt" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="5MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<param name="DatePattern" value="dd.MM.yyyy'.log'" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="file" />
</root>
</log4net>
Problem here is that, if my service is running from last 2 days, so it will not create new file with current date it keep reference of 2 days older file and adding logs into older file instead of create new file for that day.
Logger code is like
public static class Logger
{
public static log4net.ILog Log { get; set; }
static Logger()
{
Log = log4net.LogManager.GetLogger(typeof(System.Reflection.MethodBase));
}
public static void Trace(string message)
{
Log.Info(message);
}
public static void LogException(Exception ex)
{
StringBuilder builer = new StringBuilder();
builer.AppendLine("=============Exception===========");
builer.AppendLine("Exception: {0}");
builer.AppendLine("StackTrack: {1}");
Log.ErrorFormat(builer.ToString(), ex.Message, ex.StackTrace);
}
}
To log info into log file I am using code
Logger.Trace("Hello");
What is code level changes require for me to, create new log file every day even service/desktop application is running continuously from last many days?
Upvotes: 0
Views: 3946
Reputation: 23721
Your configuration has both <staticLogFileName value="false" />
and <staticLogFileName value="true" />
, which is may explain why it's not rolling correctly.
I suggest that you remove the <staticLogFileName value="true" />
and change the file and DatePattern as follows:
<file value="Logs\log-" />
...
<param name="DatePattern" value="yyyy-MM-dd'.log'" />
With staticLogFileName false, the date string will be appended to the base file name to give e.g.:
Logs\log-2018-01-30.log
I would note however that log4net will only check if it needs to roll the log file when you actually log a message, so if you aren't logging frequently, it may not roll the moment the next day begins.
Upvotes: 6