How to setup a per request global variable for NLog?

有些话、适合烂在心里 提交于 2019-12-11 08:26:00

问题


I'm working on setting up NLogs in the most useful way possible for our web applications

My thought process is as follows

  • A new request is initiated
  • A new guid is generated
  • Log webapi events w/the guid
  • Log service layer events w/the guid
  • A new guid is generated for the next request

This way it will be easy to trace the full series of events from request start to finish

There are also scenarios where I'm running service methods in parallel, if threads affect this solution

I've tried setting up the following, but ${activityid} doesn't seem to be carrying over to the output

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


回答1:


Add the value to your httpContext and read it with NLog.

E.g.

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

In your NLog.config

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

More examples in the docs

You need NLog.web or NLog.web.aspnetcore for this! Install instructions




回答2:


Ultimatley this is what I ended up doing

I setup a new class to make request data easily available anywhere in the system

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

Then I setup the global.asax to set a Guid for each request. I also added some basic rules to log the request length, fatally if longer than 1 minute

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

Then to make things easier yet, I setup a custom NLog LayoutRender so that the RequestGuid is automatically added to logging events without having to remember to include it

[LayoutRenderer("RequestGuid")]
public class RequestGuidLayoutRenderer : LayoutRenderer
{
    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        builder.Append(HttpContextRequestData.RequestGuid);
    }
}

Registered the RequestGuidLayoutRenderer in the NLog.config

 <extensions>
    <add assembly="InsertYourAssemblyNameHere"/>
 </extensions>

And finally added to my target configuration

<target name="AllLogs" xsi:type="File" maxArchiveFiles="30" fileName="${logDirectory}/AllLogs.log" layout="${longdate}|${RequestGuid}|${level:uppercase=true}|${message}|${exception:format=tostring}"


来源:https://stackoverflow.com/questions/44736889/how-to-setup-a-per-request-global-variable-for-nlog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!