我希望在我的 Serilog 输出中使用格式化的 UTC 时间戳。我编写了一个自定义丰富器,从 C# 代码调用时可以正常工作。
public class UtcTimestampEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory pf)
{
logEvent.AddPropertyIfAbsent(pf.CreateProperty("UtcTimestamp", logEvent.Timestamp.UtcDateTime));
}
}
....
var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug()
.Enrich.FromLogContext()
.Enrich.With(new UtcTimestampEnricher())
.Filter
.ByIncludingOnly( expr) // need this .Filter to ensure that
// Serilog.Filters.Expressions.dll gets loaded, else filters in config file get ignored
.WriteTo.Console(
outputTemplate: "[{UtcTimestamp:HH:mm:ss.fff} {Level:u3} {Subsystem}] {Message:lj}{NewLine}{Exception}",
restrictedToMinimumLevel: LogEventLevel.Information);
Log.Logger = loggerConfig.CreateLogger();
Run Code Online (Sandbox Code Playgroud)
现在我希望在从我的自定义 json 配置文件配置记录器时使用 utcTimestamp 扩充器。
var jsonLogconfiguration = new ConfigurationBuilder()
.AddJsonFile(logconfigFname)
.Build();
Log.Logger = new …Run Code Online (Sandbox Code Playgroud)