Kevin Kalitowski
Kevin Kalitowski

Reputation: 6989

Log4Net: Log with UTC times

Using log4net 1.2.11.0 w/ .NET, how can I get the RollingFileAppender to output UTC dates?

According to Apache it should be as easy as:

<dateTimeStrategy type="log4net.Appender.RollingFileAppender+UniversalDateTime" />

Unfortunately this is not working.

The entirety of my log4net configuration is:

  <log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <file value="Log-.txt" />
      <rollingStyle value="Date" />
      <datePattern value="yyyyMMdd"/>
      <PreserveLogFileNameExtension value="true" />
      <staticLogFileName value="false"/>
      <appendToFile value="true" />
      <maxSizeRollBackups value="10" />
      <dateTimeStrategy type="log4net.Appender.RollingFileAppender+UniversalDateTime" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <!-- Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and "OFF". -->
      <level value="DEBUG" />
      <appender-ref ref="RollingFile" />
    </root>
  </log4net>

Using a decompiler I can see that the log4net dll has the type 'UniversalDateTime' as a private class inside of RollingFileAppender.

Upvotes: 35

Views: 19723

Answers (2)

to StackOverflow
to StackOverflow

Reputation: 124696

Replace %date by %utcdate.

Example:

<conversionPattern value="%utcdate{ABSOLUTE} UTC %c{1} - %m%n" />

In this example, {ABSOLUTE} is a date format specifier: see The Log4Net PatternLayout documentation for more info.

I suspect dateTimeStrategy may be more to do with determining which midnight (local or UTC) to use when rolling by date, but am not sure about this.

Upvotes: 38

Ed DeGagne
Ed DeGagne

Reputation: 3269

Be aware that the changes are much different when using the AdoNetAppender. In that case, you need to change the parameter settings:

<parameter>
   <parameterName value="@log_date" />
   <dbType value="DateTime" />
   <layout type="log4net.Layout.RawUtcTimeStampLayout" />
   <!--<layout type="log4net.Layout.RawTimeStampLayout" />-->
</parameter>

This change will now write the correct UTC value for the logDate field.

Upvotes: 44

Related Questions