在查阅了JsNLog 文档和我在 SO(this和that)上找到的 2 篇帖子之后,仍然存在关于记录来自 JsNLog 的 RequestId 以获取 Javascript 日志条目的最佳解决方案的问号。到目前为止,我想出了这个:
(1)在_Layout.cshtml 中使用 JsNLog taghelper,但直接将 HttpContext.TraceIdentifier 放在那里,而不是使用 JSNLog.JavascriptLogging.RequestId(ViewContext.HttpContext) ,它在后台执行相同的操作:
<jl-javascript-logger-definitions request-id="@ViewContext.HttpContext.TraceIdentifier" />
(2)将 NLog 配置为使用WhenEmpty Layout Renderer。它将记录所有未设置标头“JSNLog-RequestId”(由 JsNLog javascript 提交)的事件的 HttpContext.TraceIdentifier:
<target xsi:type="File" name="allfile" fileName="log-all-${shortdate}.log"
layout="${aspnet-request:header=JSNLog-RequestId:whenEmpty=${aspnet-TraceIdentifier}} ${longdate}| ... other entries ... />
确保 NLog.config 包含
<extensions>
<!-- Make these renderers available: https://nlog-project.org/config/?tab=layout-renderers&search=package:nlog.web.aspnetcore -->
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
这样我们就可以为服务器端和客户端日志条目找到相同的 RequestId(又名 TraceIdentifier)。
该解决方案有效,并且感觉很好(在实施@Rolf Kristensen 的评论之后)。有人有更好的吗?