使用 Serilog 记录通用对象

Ste*_*ven 1 serilog

是否可以登录传入参数为通用参数的方法?例如

public async Task<TResult> Handle(TQuery query)
{
    var watch = Stopwatch.StartNew();
    var result = await _handler.Handle(query);
    watch.Stop();
    Serilog.Log.Logger.Information("Processed {@" + query.GetType().Name + "} in {Elapsed} ms",
        query.GetType().Name, watch.ElapsedMilliseconds);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

请注意,在上面,我在模板中使用字符串连接,但我不确定这是最佳实践。还有另一种方法来记录传入的对象吗?

Nic*_*rdt 6

您是否考虑过只传递查询对象的类型,或者查询对象本身?例如:

Log.Information("Processed {@Query} in {Elapsed} ms", query, watch.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)

这将打印如下输出:

Processed SomeQuery { SomeProp = "foo" } in 100 ms
Run Code Online (Sandbox Code Playgroud)