Pavle Gartner
Pavle Gartner

Reputation: 669

Log4net creates new file with old date

I implemented Console application that can run as Windows service (very similar to .NET console application as Windows service).

This is log4net config:

<?xml version="1.0" encoding="utf-8" ?>
<log4net>

  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="Log\App_%date{yyyy-MM-dd}.log" type="log4net.Util.PatternString" />
    <appendToFile value="true" />
    <param name="maxSizeRollBackups" value="5" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyy-MM-dd" />
    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
    </filter>
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%-3thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

The very first line in Main(string[] args) is log4net initialization:

XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));

Logger is initialized at the top of Program class like this:

private static readonly ILog _log = LogManager.GetLogger(typeof(Program));

When service is started/restarted or console application is ran manually, log file is created with correct filename, e.g. App_2017-11-29.log. However, if I leave windows service running over night, at midnight new file with initial date is created and old file is appended yesterdays date. So for example, if I start service today, and leave it running for 3 days, this will be in log file

Any idea why this is happening?

Upvotes: 2

Views: 919

Answers (1)

CodeCaster
CodeCaster

Reputation: 151586

The <file value="" /> element determines the "base" filename and is determined once at application startup, the <datePattern value="" /> is appended after that, and substituted with the current date in the specified format.

So your config should look like this:

<rollingStyle value="Composite" />
<file value="Log\App_" type="log4net.Util.PatternString" />
<datePattern value="yyyy-MM-dd'.log'" />
<staticLogFileName value="false" />

Upvotes: 4

Related Questions