对于在IIS集成模式下运行的应用程序,我将实现System.Web.IHttpModule,并且我希望该实现包含一个私有字段,该字段要属于“请求的范围”。以下代码说明了我的想法:
// SillyErrorLoggingHttpModule.cs
using System;
using System.Web;
using Serilog;
public class SillyErrorLoggingHttpModule : IHttpModule
{
private ILogger _logger;
public void Init(HttpApplication context)
{
context.BeginRequest += ContextOnBeginRequest;
context.Error += Context_Error;
context.EndRequest += (sender, args) => throw new ApplicationException();
}
private void ContextOnBeginRequest(object sender, EventArgs e)
{
if (sender is HttpApplication application)
{
_logger = GetLogger(application);
}
else
{
throw new ApplicationException("Toto, I've a feeling we're not in Kansas anymore.");
}
}
private void Context_Error(object sender, EventArgs e)
{
if (sender is HttpApplication application)
{
_logger.Error(application.Server.GetLastError(), "badumtss!");
}
else
{
_logger.Error("tada-da-da!");
}
}
public void Dispose()
{
}
public ILogger GetLogger(HttpApplication application)
{
// something like this:
return Log.Logger
.ForContext("url", application.Request.Url)
.ForContext("requestUUID", Guid.NewGuid().ToString());
}
}
我的目标是保持日志消息的requestUUID属性与在请求期间发生的异常之间的关系,对于该请求,我已使用requestUUID初始化_logger。但是...
我可以确定负载下的请求之间是否存在IHttpModule状态的竞争条件?
我可以假设我的日志消息在这种情况下不会混淆吗?
或者至少在referencesource上有一些文件可以检查我的假设吗?