Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLog how to access RequestId?

I want to save Activity.Current?.Id ?? HttpContext.TraceIdentifier into database, because that is Request Id which user see in default error view. But how ? HttpContext is not available in startup.cs and i tried access HttpContext in LayoutRenderer not successfully.

Error method in HomeController

public IActionResult Error()
{
    var model = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier };

    return View(model);
}

I tried LayoutRenderer

namespace Copacking.Web.Utils
{
    [LayoutRenderer("requestid")]
    public class NLogRequestIdLayoutRenderer : LayoutRenderer
    {
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            builder.Append(Activity.Current?.Id ?? HttpContext.TraceIdentifier);
        }
    }
}

but I am getting an error with HttpContext, because object reference is required.

How can i solve it ? In Nlog.config file ${aspnet-traceidentifier} is working but ${activityid} variable is empty :/

like image 574
Muflix Avatar asked Sep 17 '25 06:09

Muflix


2 Answers

You can do the following with https://www.nuget.org/packages/NLog.Web.AspNetCore:

layout="${activityid:whenEmpty=${mdlc:item=RequestId:whenEmpty=${aspnet-TraceIdentifier}}}"

Remember to include the following in NLog.config:

<extensions>
  <add assembly="NLog.Web.AspNetCore"/>
</extensions>
like image 107
Rolf Kristensen Avatar answered Sep 19 '25 21:09

Rolf Kristensen


How can i solve it ? In Nlog.config file ${aspnet-traceidentifier} is working but ${activityid} variable is empty :/

As per NLog wiki ${Activity} takes the value from Trace.CorrelationManager.ActivityId. You try assigning a value at the request start.

if(System.Diagnostics.Trace.CorrelationManager.ActivityId.Equals(Guid.Empty))
   System.Diagnostics.Trace.CorrelationManager.ActivityId = Guid.NewGuid();
like image 40
Jawahar Avatar answered Sep 19 '25 21:09

Jawahar