Skip to content

Instantly share code, notes, and snippets.

@nblumhardt
Last active October 27, 2023 18:39
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save nblumhardt/0e1e22f50fe79de60ad257f77653c813 to your computer and use it in GitHub Desktop.
Save nblumhardt/0e1e22f50fe79de60ad257f77653c813 to your computer and use it in GitHub Desktop.
Enrich.WithCaller()
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.HasMethod())
{
logEvent.AddPropertyIfAbsent(new LogEventProperty("Caller", new ScalarValue("<unknown method>")));
return;
}
var method = stack.GetMethod();
if (method.DeclaringType.Assembly != typeof(Log).Assembly)
{
var caller = $"{method.DeclaringType.FullName}.{method.Name}({string.Join(", ", method.GetParameters().Select(pi => pi.ParameterType.FullName))})";
logEvent.AddPropertyIfAbsent(new LogEventProperty("Caller", new ScalarValue(caller)));
return;
}
skip++;
}
}
}
static class LoggerCallerEnrichmentConfiguration
{
public static LoggerConfiguration WithCaller(this LoggerEnrichmentConfiguration enrichmentConfiguration)
{
return enrichmentConfiguration.With<CallerEnricher>();
}
}
class Program
{
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Enrich.WithCaller()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message} (at {Caller}){NewLine}{Exception}")
.CreateLogger();
Log.Information("Hello, world!");
SayGoodbye();
Log.CloseAndFlush();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void SayGoodbye()
{
Log.Information("Goodbye!");
}
}
}
@johannesmols
Copy link

@pmetz-steelcase great, I accepted it. And yes, that is my spin on it that I created to suit my needs better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment