如何在 NLog 的嵌套 JsonLayout 中禁用转义正斜杠符号

How to disable escaping forward-slash symbol in nested JsonLayout in NLog

我需要记录从 .Net Core 应用程序发送到外部服务的 http 请求。它工作正常,但如果 json 属性包含 / 字符,NLog 将其输出为 \/ 我想问题出在编码上,我检查了这个问题:

How to omit escaping "/" in Nlog.Web.AspNetCore

但是这些答案修复了特定 JsonAttribute 的这种行为。 如何关闭所有嵌套 JsonLayout 的编码标志?

代码示例:

static void Main(string[] args)
{
    var loggingConfig = new LoggingConfiguration();
    loggingConfig.AddRule(LogLevel.Trace, LogLevel.Fatal, new ConsoleTarget
        {
            Layout = CreateJsonLayout(),
            Encoding = Encoding.UTF8,
        });
    LogManager.Configuration = loggingConfig;

    _logger = LogManager.GetLogger("*");

    var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri("http://localhost:8080/some/path"));
    var content = new SomeClass
    {
        customerInfo = "customers/some_customers",
        boolProp = true,
        extras = "data/extras"
    };

    var eventProperties = new
    {
        Method = requestMessage.Method,
        RequestUri = requestMessage.RequestUri,
        Content = content
    };

    _logger.Log(LogLevel.Info)
        .Properties(eventProperties.AsDictionary())
        .Message("some message")
        .Write();
}

private static JsonLayout CreateJsonLayout() => new JsonLayout
{
    Attributes =
    {
        new JsonAttribute("level", "${level:upperCase=true}") { Encode = false, EscapeUnicode = false },
        new JsonAttribute("message", "${replace:searchFor=\"+:replaceWith=':regex=true:inner=${message}}") { Encode = false, EscapeUnicode = false },
        new JsonAttribute("eventProperties", 
            new JsonLayout
            {
                IncludeAllProperties = true,
                RenderEmptyObject = false,
                MaxRecursionLimit = 5,
                ExcludeProperties = new HashSet<string>(new[] { "CallerLineNumber", "CallerFilePath", "CallerMemberName" }),

            }, false) { EscapeUnicode = false }
    }
};
public class SomeClass
{
    public bool boolProp { get; set; }

    public string customerInfo { get; set; }

    public string extras { get; set; }
}
internal static class ObjectExtensions
{
    public static IDictionary AsDictionary(this object source)
    {
        return source.GetType().GetProperties().ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source)
        );
    }
}

NLog 4.6.8 已发布,允许您配置 EscapeForwardSlash

new JsonAttribute("eventProperties", 
    new JsonLayout
    {
        IncludeAllProperties = true,
        RenderEmptyObject = false,
        MaxRecursionLimit = 5,
        EscapeUnicode = false,
        EscapeForwardSlash = false,
    }, false)