簡體   English   中英

如何為NLog設置每個請求的全局變量?

[英]How to setup a per request global variable for NLog?

我正在以最有用的方式為我們的Web應用程序設置NLogs

我的思考過程如下

  • 發起新請求
  • 生成一個新的Guid
  • 使用GUID記錄WebAPI事件
  • 使用Guid記錄服務層事件
  • 為下一個請求生成一個新的Guid

這樣,可以很容易地跟蹤從請求開始到完成的所有事件

在某些情況下,如果線程影響此解決方案,我將並行運行服務方法

我嘗試設置以下內容,但${activityid}似乎沒有結轉到輸出中

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

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

例如

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

在您的NLog.config中

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

文檔中的更多示例

為此,您需要NLog.web或NLog.web.aspnetcore! 安裝說明

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM