问题描述
当前,当我在outputTemplate中使用 {Timestamp}
时,它似乎是由 DateTime.Now
和因此具有 DateTimeKind.Local
的风味,因为当我给它指定 o说明符时,它会产生类似于 2016-02-12T09:51的输出: 34.4477761-08:00
Currently when I use {Timestamp}
in an outputTemplate it appears to have been generated by DateTime.Now
and therefore being of DateTimeKind.Local
flavor since, when I give it an "o" specifier it produces output similar to 2016-02-12T09:51:34.4477761-08:00
对于上述示例,我想得到的是 2016-02- 12T17:51:34.4477761Z
,如果 Timestamp
小于。
What I'd like to get instead for the above example is 2016-02-12T17:51:34.4477761Z
, which would have been produced had the Timestamp
been of DateTimeKind.Utc
.
更新
看起来实际上是所以没有 DateTimeKind
已生效,而底层 DateTime
始终为 DateTimeKind.Unspecified
。 指出,在格式化 DateTimeOffset
与 DateTime
时的行为,特别是:
It looks like it is actually DateTimeOffset that gets instantiated there so no DateTimeKind
is in effect, rather it looks like underlying DateTime
is always of DateTimeKind.Unspecified
. MSDN notes that there is some difference in behavior when formatting DateTimeOffset
vs DateTime
, specifically:
正是我想要的转换,但我也需要分数。
The conversion is exactly what I want but I also need fractions.
推荐答案
似乎存在局限性在 DateTimeOffset
格式中将阻止此操作。
It appears the limitation in DateTimeOffset
formatting is going to thwart this.
另一种选择(只要附加属性不会膨胀输出到其他位置)是将Serilog ILogEventEnricher
添加到管道中:
An alternative (so long as the additional property doesn't bloat output somewhere else) is to add a Serilog ILogEventEnricher
to the pipeline:
class UtcTimestampEnricher : ILogEventEnricher {
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory lepf) {
logEvent.AddPropertyIfAbsent(
lepf.CreateProperty("UtcTimestamp", logEvent.Timestamp.UtcDateTime));
}
}
然后您可以使用 {在输出模板中输入UtcTimestamp:o}
即可获取所需的值。
You can then use {UtcTimestamp:o}
in your output template to get the value you need.
这篇关于是否可以将输出模板中的时间戳记获取为DateTimeKind.Utc?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!