Log4Net使用DateTime格式化 [英] DateTime Formatting with Log4Net

查看:280
本文介绍了Log4Net使用DateTime格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在使用Log4Net编写的日志文件中显示时间戳(HH:mm:ss)。我想要这个值在中央时间,但我不想要偏移出现。理想情况下,我想要阅读< HH:mm:ss> CT 。现在,我的配置设置如下:%date {HH:mm:sszzz} ,生成这个< HH:mm: ss> -05:00

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?

推荐答案

由于stuartd表示您不能在本地使用时区格式化DateTime。然而,您可以做的是创建一个自定义的 PatternLayoutConverter ,它将使用 Convert 方法中需要的任何渲染。有关参考,请参阅 DatePatternConverter 的转换方法:

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);
    }
}

m_dateFormatter 字段由您可以通过实现 IOptionHandler 界面的选项初始化。

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>

这篇关于Log4Net使用DateTime格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆