2017-06-24 68 views
1

我工作中最有用的可能的方式爲我們的web應用程序如何爲NLog設置每個請求全局變量?

設立NLogs

我的思維過程如下:

  • 一個新的請求啓動
  • 產生
  • 新的GUID
  • 登錄的WebAPI事件瓦特/ GUID
  • 日誌服務層事件瓦特/ GUID
  • 爲下一個請求而生成新的GUID

這樣,它會很容易追查全系列事件的請求開始到結束

也有在那裏我並行運行服務方法的情況,如果線程影響該解決方案

我試過設置以下,但${activityid}似乎並沒有被攜帶到輸出

https://github.com/NLog/NLog/wiki/Trace-Activity-Id-Layout-Renderer

回答

1

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}" 
1

值添加到您的httpContext並用NLog讀取它。

E.g.

HttpContext.Current.Items["myvariable"] = 123; 

在你NLog.config

${aspnet-item:variable=myvariable} - produces "123" 

More examples in the docs

你需要NLog.web或NLog.web.aspnetcore此! Install instructions