DateTime formatting with Log4Net

I want to display a timestamp (HH: mm: ss) in a log file that is written using Log4Net. I want this value to be in central time, but I don't want the offset to appear. Ideally I would like to read <HH:mm:ss> CT

. Right now my config is set up like this: %date{HH:mm:sszzz}

which produces this <HH:mm:ss>-05:00

. What would be the correct format specifier to create this timestamp format?

+3


source to share


1 answer


As stuartd said, you cannot format DateTime with timezones natively. However, you can create a custom PatternLayoutConverter

one that will use whatever rendering you want in the method Convert

. For reference, here's a Convert method for 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 field is m_dateFormatter

initialized with parameters that you can pass to them by implementing the interface IOptionHandler

.



Once you have the 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>

      

+2


source







All Articles