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

时间:2019-07-18 12:09:39

标签: c# nlog

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

NLog: logging an object serialized to JSON

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

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

代码示例:

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)
        );
    }
}

1 个答案:

答案 0 :(得分:3)

NLog 4.6.8已发布,可让您配置EscapeForwardSlash

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