serilog
serilog copied to clipboard
Design question: support scopes for ILogEventSink
Current Limitation
Right now, it's not possible for sinks to detect when a scope is created using ILogger.BeginScope
. Although Serilog internally tracks scopes using SerilogScopeProvider
and LogContext, sinks don't have the ability to intercept scope creation or disposal events to add custom code.
Proposed Solution: I suggest implementing an ISinkScopeFactory that could be associated with a sink. This would provide a more straightforward way to handle scoping.
Use Case:
A key application of this feature is to link parent and child logs. While it's possible to do this using properties, specialized outputs like Application Insights allow the use of an OperationId
. Such a feature enhances the ability to navigate logs in the built-in UI. Currently, without this proposed support, implementing a feature to link logs is challenging. The only workaround is to track the scope values when a log is emitted, but this feels like a makeshift solution.
Code Example:
using var scope = _logger.BeginScope("My operations group");
_logger.LogInformation("This log should have the ParentId property set to the Dependency property");
Desired Behavior:
Upon calling BeginScope
, I would like to initiate dependency tracking and set up my internal state (possibly utilizing ActivityContext). All subsequent operations within this scope should have their ParentId
set to the one created with BeginScope.
Why this issue is open I'm curious about the design considerations that led to this feature not being included initially. Do the original developers see that implementing this would break the initial design of Serilog or would be a plus to have it?
Hi! I think what you're looking for is covered by https://github.com/serilog-tracing/serilog-tracing, though we haven't tried it out in combination with AppInsights yet.
The parent id property there is called ParentSpanId
.
Hope this helps!
Nick
Thank you, @nblumhardt, indeed you can resolve this in a bunch of ways including the nuget you have mentioned. Activity offers ways to log in the same process via SpanId or cross-distributed systems.
However, my question was more oriented to design and the reasons behind Serilog does not implement this, since there is the notion parent - child added implicitly bu the ILogger scopes.
Thanks for your reply @dtila. Unfortunately there's limited time to dig in deeply on past design decisions here, so I'll close this as we're not expecting it will lead to changes in Serilog itself.
Now that Activity
and the related tracing features of .NET are so widespread, it doesn't make a lot of sense to implement something different here in Serilog, but if you can try out SerilogTracing and send feedback there it'll be appreciated. Thanks again!