-
-
Save Suchiman/59e9064614517e77c598af721c9e1261 to your computer and use it in GitHub Desktop.
Enrich.WithCaller()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
using Serilog; | |
using Serilog.Configuration; | |
using Serilog.Core; | |
using Serilog.Events; | |
namespace ConsoleApp24 | |
{ | |
class CallerEnricher : ILogEventEnricher | |
{ | |
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) | |
{ | |
var skip = 3; | |
while (true) | |
{ | |
var stack = new StackFrame(skip); | |
if (stack.GetMethod() is not { } method) | |
{ | |
return; | |
} | |
if (method.DeclaringType.Assembly != typeof(Log).Assembly) | |
{ | |
var caller = $"{method.DeclaringType.Name}.{method.Name}({string.Join(", ", method.GetParameters().Select(pi => pi.ParameterType.FullName))})"; | |
logEvent.AddOrUpdateProperty(new LogEventProperty("SourceContext", new ScalarValue(caller))); | |
return; | |
} | |
skip++; | |
} | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Log.Logger = new LoggerConfiguration() | |
.Enrich.With<CallerEnricher>() | |
.WriteTo.Console() | |
.CreateLogger(); | |
Log.Information("Hello, world!"); | |
SayGoodbye(); | |
Log.CloseAndFlush(); | |
} | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
static void SayGoodbye() | |
{ | |
Log.Information("Goodbye!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment