问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/10012083/log4net-log-with-utc-times