Using Serilog to log generic object

serilog

Solution

Have you considered just passing the type of the query object through, or the query object itself? E.g.:

Log.Information("Processed {@Query} in {Elapsed} ms", query, watch.ElapsedMilliseconds);

This will print output like:

Processed SomeQuery { SomeProp = "foo" } in 100 ms

Problem

Is it possible to log in a method where the incoming argument is generic? For example ``` 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; } ``` Note in the above, I'm using string concatenation in the template and I'm not sure this is a best practice. Is there another way to log the incoming object?

Original source