Search code examples
vb.netserilog

Serilog - Output/Enrich All Messages with MethodName from which log entry was Called


Is there anyway to enrich all Serilog output with the Method Name.

For Instance consider If I have the following;

Public Class MyClassName

  Private Function MyFunctionName() As Boolean
      Logger.Information("Hello World")
      Return True
  End Function

End Class

The desired output would be as follows;

2015-04-06 18:41:35.361 +10:00 [Information] [MyFunctionName] Hello World!

Actually the Fully Qualified Name would be good.

2015-04-06 18:41:35.361 +10:00 [Information] [MyClassName.MyFunctionName] Hello World!

It seems that "Enrichers" are only good for Static Information and won't work each time.


Solution

  • It's possible to do this with an enricher by reflecting over the call stack, but very expensive to do so, so Serilog doesn't offer it.

    Instead you can use something like:

    Logger.Here().Information("Hello, world!");
    

    and implement the Here() method as an extension method on ILogger:

    <Extension>
    Public Sub Here(ByVal logger as ILogger,
        <CallerMemberName> Optional memberName As String = Nothing)
    
        Return logger.ForContext("MemberName", memberName)
    End Sub