首页 > 解决方案 > 将 NLog 与 .Net Core 一起使用时,aspnet-request:serverVariable 的任何替代方案?

问题描述

NLog GitHub 上所述 ${aspnet-request:serverVariable=String},.Net Core 不支持布局渲染器。
该文档没有提供 serverVariable 下许多可用变量的替代方案。

我的问题是,有没有其他选择?喜欢访问远程地址、服务器名称、端口等?还是我只需要编写一堆自定义布局渲染器然后手动依赖注入所有东西?

标签: asp.net-coreloggingnlog

解决方案


对于 ASP.NET Core,有许多新的布局呈现。原因是 ASP.NET Core 的 API 非常不同,无法像 ASP.NET 中那样读取服务器变量(所以非核心)

当前有 13 个用于 ASP.NET Core 的布局呈现器,用于呈现请求的一部分。

  • ${aspnet-request} - ASP.NET 请求变量。
  • ${aspnet-request-contenttype} - ASP.NET Content-Type 标头(例如 application/json)
  • ${aspnet-request-cookie} - ASP.NET 请求 cookie 内容。
  • ${aspnet-request-form} - ASP.NET 请求表单内容。
  • ${aspnet-request-headers} - ASP.NET 标头键/值对。
  • ${aspnet-request-host} - ASP.NET 请求主机
  • ${aspnet-request-ip} - 客户端 IP。
  • ${aspnet-request-method} - ASP.NET 请求方法(GET、POST 等)。
  • ${aspnet-request-posted-body} - ASP.NET 发布的正文/有效负载
  • ${aspnet-request-querystring} - ASP.NET 请求查询字符串。
  • ${aspnet-request-referrer} - ASP.NET 请求引荐来源网址。
  • ${aspnet-request-url} - ASP.NET 请求 URL。
  • ${aspnet-request-useragent} - ASP.NET 请求用户代理。

另请参阅https://nlog-project.org/config/?tab=layout-renderers&search=package:nlog.web.aspnetcore

如果你需要别的东西,你确实可以创建一个自定义渲染器。如果您需要 http 请求,您可以使用:

AspNetLayoutRendererBase.Register("aspnet-request-myrenderer", (logevent, httpcontext, config) => ... );

您需要为此参考 NLog.Web.AspNetCore 包。


推荐阅读