4

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?

nobody
  • 19,814
  • 17
  • 56
  • 77
Dan Forbes
  • 2,734
  • 3
  • 30
  • 60
  • .Net DateTime format strings don't support Time Zone names.. – stuartd Sep 11 '14 at 16:20
  • @Dan, did you manage to handle the date formatting in your log? – samy Sep 22 '14 at 10:18
  • I haven't had the opportunity to try this out. I'm sorry...I know I need to accept your answer or comment with why it's not acceptable - I just haven't had the time. I have not forgotten, though, and I appreciate that you took the time to answer my question. I promise to follow with results ASAP! – Dan Forbes Sep 22 '14 at 15:15

1 Answers1

4

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>
samy
  • 14,832
  • 2
  • 54
  • 82