如何防止$ {aspnet-request-posted-body}不记录敏感信息

时间:2020-10-21 19:57:21

标签: c# logging nlog

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

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

请注意,我已经尝试过解决此问题的布局,并且不想使用它。还有其他方法可以完成此任务吗?

1 个答案:

答案 0 :(得分:1)

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

因此,您有以下选择:

  • 用正则表达式替换所有内容:使用replace all的配置示例:

    <variable name="messageNoDigits" 
      value="${replace:inner=${message}:searchFor=(\\d{3\})+:replaceWith=:regex=true}" />
    
  • 编写您自己的自定义布局渲染器,该渲染器将正文解析为JSON并将其转换。请注意,在ASP.NET Core中阅读正文可能有些棘手,请参阅the current code in NLog for it。如果您具有用于读取/转换主体的代码,则可以轻松地将其转换为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