【问题标题】:Is it possible to get Timestamp in output template as DateTimeKind.Utc?是否可以在输出模板中获取时间戳作为 DateTimeKind.Utc?
【发布时间】:2016-02-12 18:14:31
【问题描述】:

目前,当我在 outputTemplate 中使用{Timestamp} 时,它似乎是由DateTime.Now 生成的,因此属于DateTimeKind.Local 风格,因为当我给它一个“o”说明符时,它会产生类似于2016-02-12T09:51:34.4477761-08:00 的输出

对于上面的例子,我想得到的是2016-02-12T17:51:34.4477761Z,如果TimestampDateTimeKind.Utc,就会产生它。

更新

看起来它实际上是DateTimeOffset that gets instantiated there,所以没有DateTimeKind 生效,而是看起来底层DateTime 总是DateTimeKind.UnspecifiedMSDN 注意到格式化 DateTimeOffsetDateTime 时的行为存在一些差异,特别是:

"u" -- 将 DateTimeOffset 值转换为 UTC 并使用格式 yyyy-MM-dd HH:mm:ssZ 输出。

转换正是我想要的,但我也需要分数。

【问题讨论】:

    标签: .net serilog


    【解决方案1】:

    看来DateTimeOffset 格式的限制会阻碍这一点。

    另一种选择(只要附加属性不会使输出在其他地方膨胀)是将 Serilog ILogEventEnricher 添加到管道:

    class UtcTimestampEnricher : ILogEventEnricher {
      public void Enrich(LogEvent logEvent, ILogEventPropertyFactory lepf) {
        logEvent.AddPropertyIfAbsent(
          lepf.CreateProperty("UtcTimestamp", logEvent.Timestamp.UtcDateTime));
      }
    }
    

    然后您可以在输出模板中使用{UtcTimestamp:o} 来获取您需要的值。

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 2014-12-13
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      相关资源
      最近更新 更多