如何将 log4net aspnet-request 转换模式用于关联 ID

How do I use the log4net aspnet-request conversion pattern for a correlation id

我想为每个错误分配一个关联 ID,并将其放入由 log4net 生成的日志文件中。我想要这样,这样我就可以在自定义的错误页面中将其显示给用户,然后我们的操作人员可以将它们匹配起来并知道是哪个错误。

我设置了一个没有ActionFilterAttribute的:

public class RequestModificationForLoggingFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext.Current.Request.Headers["correlationid"] = Guid.NewGuid().ToString();
    }
}

并将 log4net.config 更改为(注意 [%aspnet-request{correlationid}]):

  <conversionPattern value=" %utcdate [%aspnet-request{correlationid}] [P%property{processId}/D%property{appDomainId}/T%thread] %-5level %logger - %message%newline" />

但日志最后显示 [NOT AVAILABLE]:

2017-03-21 14:40:18,151 [NOT AVAILABLE] [P54916/D3/T83] WARN  - blahblahblah

我哪里错了?

我最终创建了一个模块:

public class LoggingModule : IHttpModule
{
    public void Dispose()
    {
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(OnBeginRequest);
    }

    public void OnBeginRequest(Object sender, EventArgs e)
    {
        // When the error event is called, we set a correlation id which gets used in the logging
        ThreadContext.Properties["correlationid"] = Guid.NewGuid().ToString();
    }
}

然后使用了这个 log4net 语法:

%property{correlationid}

不要忘记,如果您想要从 applicationstartup 或类似的东西跟踪的任何东西的 ID,您可以检查您的跟踪侦听器,例如:

// If correlationid is not set, then this log was thrown from a place where a request was not made. ie. OnApplicationStarting
if (ThreadContext.Properties["correlationid"] == null)
{
    // We assign an id here to ensure the log does not show null for id
    ThreadContext.Properties["correlationid"] = Guid.NewGuid().ToString();
}