C#C
C#4mo ago
15 replies
yanilov

How do caller information attributes fit into structured logging?

It seems like the standard Microsoft Ilogger takes structured arguments with as params object[] , making it hard to combine it with caller attributes such as [CallerMemberName] .
I know that caller information can be added for source-generated logging with [LoggerMessage] or [LogProperties] attributes on an ad-hoc basis, but I'm looking for an infrastructural solution.
How are you dealing with injecting caller information at scale in your code base?

I thought creating an interface
class ILogContext<T> {
    ILogger Ctx([CallerMemberName] string callerMemberName = "");
}


which is injected everywhere instead of a plain
ILogger
and have the implementation be

class LogContext<T> {
    private readonly ILoggerFactory _factory;
    LogContext(ILoggerFactory factory){
       _factory = factory;
    }

    ILogger Ctx([CallerMemberName] string callerMemberName = ""){
        var logger =  _factory.CreateLogger<T>();
        logger.BeginScope("callerMemberName", callerMemberName);
        return logger;
    }
}


but this approach seems subpar
Was this page helpful?