Ultimatley這是我最後做
我建立一個新的類,使容易在系統
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);
}
}
註冊RequestGuidLayoutRenderer在NLog.config
<extensions>
<add assembly="InsertYourAssemblyNameHere"/>
</extensions>
最後加入到我的TA rget配置
<target name="AllLogs" xsi:type="File" maxArchiveFiles="30" fileName="${logDirectory}/AllLogs.log" layout="${longdate}|${RequestGuid}|${level:uppercase=true}|${message}|${exception:format=tostring}"