DateTime Formatting with Log4Net

时光总嘲笑我的痴心妄想 提交于 2019-12-10 17:53:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!