问题
I'd like to display a timestamp (HH:mm:ss) in a log file that's written using Log4Net. I want this value to be in Central Time, but I don't want the offset to appear. Ideally, I'd like it to read <HH:mm:ss> CT
. Right now, my config is set up like this: %date{HH:mm:sszzz}
, which is producing this <HH:mm:ss>-05:00
. What would be the proper format specifier to produce this timestamp format?
回答1:
As stuartd said you cannot format DateTime with Time Zones natively. What you can do however is to create a custom PatternLayoutConverter
that would use whichever rendering you need in the Convert
method. For reference here is the Convert method for the DatePatternConverter
:
// log4net.Layout.Pattern.DatePatternConverter
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
try
{
this.m_dateFormatter.FormatDate(loggingEvent.TimeStamp, writer);
}
catch (Exception exception)
{
LogLog.Error("DatePatternConverter: Error occurred while converting date.", exception);
}
}
The m_dateFormatter
field is initialized by options you can pass it by implementing the IOptionHandler
interface.
Once you have your converter, add it to your layout by declaring it inside the layout tag
<layout ...>
<converter>
<name value="myDateWithTimeZone" />
<type value="MyApp.LogConverters.MyConverter" />
</converter>
<!-- rest of the layout -->
</layout>
来源:https://stackoverflow.com/questions/25789752/datetime-formatting-with-log4net