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

时间:2017-03-21 14:44:44

标签: umbraco log4net

我希望为log4net生成的日志文件中的每个错误分配一个相关ID。我想这样,以便我可以在自定义错误页面中将其显示给用户,然后我们的操作可以匹配它们并知道哪个错误。

我设置了一个没有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" />

但是日志最终说[不可用]:

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

我哪里错了?

1 个答案:

答案 0 :(得分:0)

我最终创建了一个模块:

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();
}