Log CorrelationId with SerilogWeb.Classic's log entries
mattheys opened this issue · comments
I was looking to find a way I can push a Correlation Id into SerilogWeb.Classic's log events similar to the suggestion in #72 response.
If I push a property in the OnPreInit and dispose of it at the end of Page_Load it works ok for requests that actaully make it to my page e.g. not 401 errors.
If I dispose of my CorrelationId in the OnUnload it isn't logged with SerilogWeb.Classic's log events.
What is the best place to do this? I need to manage the CorrelationId myself so I can return it to the User if there is an issue and I don't think you can read Serilog properties once pushed.
not 100% sure if I understand correctly 🤔
- Why do you need to "dispose" of your
CorrelationId
in theOnUnload
? would "not disposing it" allow it to still exist at the moment where SerilogWeb logs the event ? - wouldn't using or copying/adapting the current
HttpRequestIdEnricher
help ? note that it exposesstatic
accessor in case you need access to the Id of the current request
Sorry I wasn't clear, I meant about disposing of the IDisposable property from PushProperty("CorrelationId",correlationId)
I was using.
I've taken this approach instead since it's a simple single api that returns a document based on url properties and there is no state to manage, I just abandon the session before the page ends. I will take a look at the TryGetCurrentHttpRequestId and see if that helps as well.
static Dictionary<Guid, IDisposable> logProperties = new Dictionary<Guid, IDisposable>();
protected void Session_Start(object sender, EventArgs e)
{
var guid = Guid.NewGuid();
Session["CorrelationId"] = guid;
IDisposable logProperty = Serilog.Context.LogContext.PushProperty("CorrelationId", guid);
Log.Verbose("Session {CorrelationId} started", guid);
logProperties.Add(guid, logProperty);
}
protected void Session_End(object sender, EventArgs e)
{
Guid? guid = Session["CorrelationId"] as Guid?;
if (!guid.HasValue)
{
Log.Verbose("Session with no CorrelationId ended, {CorrelationIdCount} in dictionary", logProperties.Count);
return;
}
Log.Verbose("Session {CorrelationId} ended", guid);
if (logProperties.TryGetValue(guid.Value, out var log))
{
log.Dispose();
logProperties.Remove(guid.Value);
}
}