1

After consulting the JsNLog docs and the 2 posts I found on SO (this and that) there were still question marks about the best solution for logging the RequestId coming from JsNLog for Javascript log entries. So far I came up with this:

(1) In _Layout.cshtml use the JsNLog taghelper, but place the HttpContext.TraceIdentifier there directly, instead of using JSNLog.JavascriptLogging.RequestId(ViewContext.HttpContext) which does the same under under the hood:

<jl-javascript-logger-definitions request-id="@ViewContext.HttpContext.TraceIdentifier" />

(2) Configure NLog to used the WhenEmpty Layout Renderer. It will log the HttpContext.TraceIdentifier for all events where the header "JSNLog-RequestId" (submitted by JsNLog javascript) is not set:

<target xsi:type="File" name="allfile" fileName="log-all-${shortdate}.log"
        layout="${aspnet-request:header=JSNLog-RequestId:whenEmpty=${aspnet-TraceIdentifier}} ${longdate}| ... other entries ... />

Make sure the the NLog.config contains

<extensions>
  <!-- Make these renderers available: https://nlog-project.org/config/?tab=layout-renderers&search=package:nlog.web.aspnetcore -->
  <add assembly="NLog.Web.AspNetCore"/>
</extensions>

This way we find the same RequestId (aka TraceIdentifier) for server side and client side log entries which belong together.

This solution works, and feels quite okay (after @Rolf Kristensen's comments were implemented). Does anyone have a better one?

axuno
  • 581
  • 4
  • 15
  • 1
    Have no advice about integration of JsNLog, but consider changing the NLog coalesce into this: `"${mdc:item=JsNLogTraceIdentifier:whenEmpty:${aspnet-TraceIdentifier}} .."` (Much cleaner and much faster) – Rolf Kristensen Dec 02 '18 at 12:21
  • 1
    Maybe you can skip the hook into OnLogging with this: `"${aspnet-request:header=JSNLog-RequestId:whenEmpty=${aspnet-TraceIdentifier}} .. "` – Rolf Kristensen Dec 02 '18 at 16:17
  • More advanced version, that also checks AspNetCore-Header: `"${aspnet-request:header=JSNLog-RequestId:whenEmpty=${mdlc:item=RequestId:whenEmpty=${aspnet-TraceIdentifier}}} ..."` – Rolf Kristensen Dec 02 '18 at 17:31
  • 1
    @Rolf Kristensen: With your first two modifications I think it's a lot better, especially because the OnLogging hook went away. I updated the solution accordingly. Tnx – axuno Dec 02 '18 at 17:53

0 Answers0