Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

.net - Is it possible to get Timestamp in output template as DateTimeKind.Utc?

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

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.

Update

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:

"u" -- Converts the DateTimeOffset value to UTC and outputs it using the format yyyy-MM-dd HH:mm:ssZ.

The conversion is exactly what I want but I also need fractions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It appears the limitation in DateTimeOffset formatting is going to thwart this.

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

You can then use {UtcTimestamp:o} in your output template to get the value you need.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...