C
C#3w ago
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 = "");
}
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;
}
}
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
3 Replies
Unknown User
Unknown User3w ago
Message Not Public
Sign In & Join Server To View
yanilov
yanilovOP2w ago
Stacktrace approach is out of the question I'm afraid, it's the solution I'm migrating away from So @TeBeCo your flow is to track down either a unique-ish log message or an eventId in your codebase?
Unknown User
Unknown User2w ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?