这就是我最终要做的事情
我设置了一个新类,以使请求数据在系统的任何地方都可以轻松访问
public static class HttpContextRequestData
{
public static string RequestGuid
{
get
{
if (HttpContext.Current.Items["RequestGuid"] == null)
return string.Empty;
else
return HttpContext.Current.Items["RequestGuid"] as string;
}
set
{
HttpContext.Current.Items["RequestGuid"] = value;
}
}
public static DateTime RequestInitiated
{
get
{
if (HttpContext.Current.Items["RequestInitiated"] == null)
return DateTime.Now;
else
return Convert.ToDateTime(HttpContext.Current.Items["RequestInitiated"]);
}
set
{
HttpContext.Current.Items["RequestInitiated"] = value;
}
}
}
然后我设置 global.asax 为每个请求设置一个 Guid。我还添加了一些基本规则来记录请求长度,如果超过 1 分钟则致命
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContextRequestData.RequestGuid = Guid.NewGuid().ToString();
HttpContextRequestData.RequestInitiated = DateTime.Now;
logger.Info("Application_BeginRequest");
}
void Application_EndRequest(object sender, EventArgs e)
{
var requestAge = DateTime.Now.Subtract(HttpContextRequestData.RequestInitiated);
if (requestAge.TotalSeconds <= 20)
logger.Info("Application_End, took {0} seconds", requestAge.TotalSeconds);
else if (requestAge.TotalSeconds <= 60)
logger.Warn("Application_End, took {0} seconds", requestAge.TotalSeconds);
else
logger.Fatal("Application_End, took {0} seconds", requestAge.TotalSeconds);
}
然后,为了让事情变得更简单,我设置了一个自定义 NLog LayoutRender,以便 RequestGuid 自动添加到日志记录事件中,而无需记住包含它
[LayoutRenderer("RequestGuid")]
public class RequestGuidLayoutRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(HttpContextRequestData.RequestGuid);
}
}
在NLog.config中注册了RequestGuidLayoutRenderer
<extensions>
<add assembly="InsertYourAssemblyNameHere"/>
</extensions>
最后添加到我的目标配置中
<target name="AllLogs" xsi:type="File" maxArchiveFiles="30" fileName="${logDirectory}/AllLogs.log" layout="${longdate}|${RequestGuid}|${level:uppercase=true}|${message}|${exception:format=tostring}"