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

3,675 views
Skip to first unread message

Aaron Glover

unread,
Apr 6, 2015, 8:12:29 PM4/6/15
to ser...@googlegroups.com

Hi All,

I posted this at StackOverflow; http://stackoverflow.com/q/29470863/4022049


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.


Thanks!

Aaron Glover

unread,
Apr 8, 2015, 9:57:54 PM4/8/15
to ser...@googlegroups.com
Nick answered this on Stackoverflow.....


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

Aaron Glover

unread,
Apr 10, 2015, 9:04:31 AM4/10/15
to ser...@googlegroups.com
I do wonder just how much overhead this adds. .. it seems to be a fundamental feature of most logging libraries. 

It would be nice if this was just a built-in enricher or configuration option... turned off by default but if people are prepared to take the hit then they can turn it on. 

It would remove the requirement to write code constantly to call the extension method

nblum...@nblumhardt.com

unread,
Apr 10, 2015, 7:14:05 PM4/10/15
to ser...@googlegroups.com
In case it helps - Anotar.Fody's Serilog support does add this, as close to zero-cost as possible: https://github.com/Fody/Anotar

(This solution uses IL rewriting, which does the job but may not appeal to everyone.)

Cheers,
Nick
Reply all
Reply to author
Forward
0 new messages