如何配置 nlog.config 以包含 asp.net core 2 web api 请求自定义 header 信息?

How to configure nlog.config to include asp.net core 2 web api request custom header information?

我有一个简单的 asp.net 核心网络 api 应用程序(使用 Visual Studio 2017 中的默认网络 api 模板)使用 nlog 将消息记录到控制台 JSON格式。

这里是 NLog 配置文件:

 <!-- the targets to write to -->
 <targets>
    <target xsi:type="Console" name="console_log" >
      <layout xsi:type="JsonLayout">
        <attribute name="ts" layout="${date}" />
        <attribute name="level" layout="${level:upperCase=true}"/>
        **<attribute name="all-events" layout="${all-event-properties}"/>
        <attribute name="tid" layout="${aspnet-request:header=tid}"/>**
        <attribute name="cn" layout="${callsite}"/>
        <attribute name="msg" layout="${message}" />
      </layout>
    </target>
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Debug" writeTo="console_log" />
  </rules>
</nlog>

在Startup.cs中,Configure方法包含以下两行:

        env.ConfigureNLog("nlog.config");
        loggerFactory.AddNLog();

我将 JSON 格式的日志消息输出到控制台。但是,我无法在 HTTP 请求 header.

中收到自定义 header 的 tid

如何提取 HTTP 请求 header 并将其输出到控制台?

感谢您的 comments/answers/guidance。谢谢。

您可以像这样使用 ActionFilterAttribute

public class HttpHeadersLogger : ActionFilterAttribute
{
    private readonly Logger _log = LogManager.GetCurrentClassLogger();

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request = filterContext.HttpContext.Request;
        var builder = new StringBuilder();

        builder.Append(request.RequestType + " " + request.Url + "\n");

        var logEventInfo = new LogEventInfo(LogLevel.Info, null, null);
        var parsed = HttpUtility.ParseQueryString(request.Headers.ToString());

        foreach (string key in parsed)
        {
            // Search for 'tid' header here to only log these one
            logEventInfo.Properties.Add(key, parsed[key]);
        }

        _log.Log(logEventInfo);

        base.OnActionExecuting(filterContext);
    }
}

在这个例子中,所有 headers 都被记录,如果你只想要 'tid' 一个,你应该过滤掉它。 这将使用 NLog 布局表达式,通过使用 object LogEventInfo 来执行日志操作。

${aspnet-request} 取决于 HttpContextAccessor。请更新您的代码以在 IWebHostBuilder 上使用 UseNLog(参见本例中的 program.cs)

https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2#4-update-programcs

UseNLog 会自动注册 HttpContextAccessor(记得删除任何 ConfigureNLogAddNLog 的用法,但只使用 UseNLogLogManager.LoadConfiguration 如上例所示)