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 :/
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>
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With