serilog / serilog-extensions-logging

Serilog provider for Microsoft.Extensions.Logging
Apache License 2.0
313 stars 100 forks source link

Accessing the exception argument from formatter Func<state,ex,string> cause NullRef #159

Closed cs101 closed 4 years ago

cs101 commented 4 years ago

Hi, I'm very new to Serilog, I'm trying to call the MEL ILogger.Log(... ex, Func<state,ex,string> formatter) method with a formatter like this: (state, ex)=>$"{ex.Message}", which gives me NullRef exception. and after going through the code, it's coming from this method in

serilog-extensions-logging/src/Serilog.Extensions.Logging/Extensions/Logging/SerilogLogger.cs

static object AsLoggableValue(TState state, Func<TState, Exception, string> formatter) { object sobj = state; if (formatter != null) sobj = formatter(state, null); return sobj; }

shouldn't it also pass the exception argument alone instead of hardcoding it to 'null' ? thanks!

nblumhardt commented 4 years ago

Hi! Thanks for the note.

Serilog always considers the exception separately from other log event state, hence in this case Serilog only defers formatting of the remainder of the state payload to the formatter, since we don't want to duplicate exception information in the message.

I'm not sure whether changing tack here is an option - I can see how the exception might reasonably be expected to be passed to the callback, but there's a trade-off and it'd need some deeper investigation into what kinds of formatters we might hit, and how the resulting log events will appear.

In case your question was simply "is this a bug", no, it's by design - but open to improvement if there's a good case for it. Cheers!

cs101 commented 4 years ago

thanks for the reply, I was suspecting it's by design since serilog handle exception in its own way, just wanted to confirm. thanks!

nblumhardt commented 4 years ago

Thanks for the follow-up 👍