首页 > 解决方案 > 如何防止 ${aspnet-request-posted-body} 不记录敏感信息

问题描述

我正在使用 ${aspnet-request-post-body} 将请求正文记录在日志文件中。我面临的问题:我想防止${aspnet-request-post-body}记录一些信息,即密码和信用卡详细信息,我喜欢对它们应用屏蔽。

例如,如果请求正文是 {username : ABC, password :554&3} 这应该以这种格式记录 {username: ABC, password : ****}

请注意,我已经尝试过替换布局来解决这个问题,不想使用它。有没有其他方法可以完成这项任务?

标签: c#loggingnlog

解决方案


${aspnet-request-post-body}是 NLog 的唯一文本。

因此,您有以下选择:

  • 替换所有东西(使用正则表达式):替换全部的配置示例:

    <variable name="messageNoDigits" 
      value="${replace:inner=${message}:searchFor=(\\d{3\})+:replaceWith=:regex=true}" />
    
  • 编写您自己的自定义布局渲染器,将主体解析为 JSON 并对其进行转换。请注意,在 ASP.NET Core 中阅读正文可能有点棘手,请参阅NLog 中的当前代码。如果你有读取/转换正文的代码,它可以很容易地转换为 NLog 布局渲染器:

    using NLog.Web.LayoutRenderers; 
    
    // register ${SanitizedBody}
    AspNetLayoutRendererBase.Register("SanitizedBody", (logEventInfo, httpContext, loggingConfiguration) => MyMethod(httpContext));
    

    请参阅https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer


推荐阅读