Enterprise Library Logging App Block的时区问题

本文介绍如何在Enterprise Library中将日志记录的时间戳从UTC时间转换为本地时间的方法,通过覆盖FormatToken方法实现。

LAB记录的日志里timestamp总是UTC时间,很是郁闷,只能把里面的DateTime.UtcNow改成DateTime.Now,再编译引用。

 

今天偶然看见http://blogs.msdn.com/tomholl/archive/2006/01/22/516055.aspx讲到可以修改TimeStampToken 的FormatToken方法:

/// <summary> /// Formats the timestamp property with the specified date time format string. /// </summary> /// <param name="tokenTemplate">Date time format string. Prefix with 'local:' to convert to local time.</param> /// <param name="log">Log entry containing the timestamp.</param> /// <returns>Returns the formatted time stamp.</returns> public override string FormatToken(string tokenTemplate, LogEntry log) { if (tokenTemplate.Equals("local", System.StringComparison.InvariantCultureIgnoreCase)) { System.DateTime localTime = log.TimeStamp.ToLocalTime(); return localTime.ToString(); } else if (tokenTemplate.StartsWith("local:", System.StringComparison.InvariantCultureIgnoreCase)) { string formatTemplate = tokenTemplate.Substring(6); System.DateTime localTime = log.TimeStamp.ToLocalTime(); return localTime.ToString(formatTemplate, CultureInfo.CurrentCulture); } else { return log.TimeStamp.ToString(tokenTemplate, CultureInfo.CurrentCulture); } }

然后,

Timestamp: {timestamp}
Timestamp local: {timestamp(local)}
Timestamp F: {timestamp(F)}
Timestamp local:F {timestamp(local:F)}

结果:

Timestamp: 1/23/2006 2:24:18 AM
Timestamp local: 1/22/2006 6:24:18 PM
Timestamp F: Monday, January 23, 2006 2:24:18 AM
Timestamp local:F Sunday, January 22, 2006 6:24:18 PM

 

马上去源码里看看,晕,原来源码里早就是这段了,那为嘛没人告诉我可以这样用呢?连配置工具里也没这标签啊!

 

PS:这次看的源码版本是Enterprise Library 3.1 - May 2007,不知道后来版本配置工具里有没有。

转载于:https://www.cnblogs.com/honker/archive/2009/07/27/3774427.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值