如何在C#.NET结构化日志记录中强制使用驼峰大小写?

时间:2019-12-10 23:30:32

标签: c# asp.net-core logging nlog structured-logging

有人知道如何将.NET Core C#中的结构化日志记录的行为/格式更改为驼峰式(例如:camelCase)吗?我正在尝试利用结构化日志记录,如下所示:

Logger.LogInformation("Some text here. My object: {@some_class}", someClass);

让我们说一些类如下:

class SomeClass {
  [JsonProperty(PropertyName = "intField")] // this does NOT work for structured logging
  int IntField {get;set;}
  string StrField {get;set;}
}

为简洁起见,我将收到如下输出:

{
  ...
  "message": "Some text here. My object: {\"IntField\":5,\"StrField\":\"I'm here\"}",
  "some_class": {
    "IntField":5,
    "StrField":"I'm here"
  },
  ...
}

但是我想要的是所有字段都是驼峰式,就像日志中的所有父字段一样。以下是理想的结果:

{
  ...
  "message": "Some text here. My object: {\"IntField\":5,\"StrField\":\"I'm here\"}",
  "some_class": {
    "intField":5,
    "strField":"I'm here"
  },
  ...
}

我尝试使用新的JsonSerializerSettings对象设置我的JsonConvert.DefaultSettings以强制使用驼峰式大小写,但是我假设只有在实际序列化为字符串(got this from StackOverflow question)时,此方法才有效。我猜记录器没有在后台使用。

如果有帮助,我正在使用.NET Core 2.2和v4.8.1。

1 个答案:

答案 0 :(得分:1)

1)使用CamelCaseNamingStrategy作为NamingStrategy配置创建自定义序列化程序

    internal class JsonNetSerializer : NLog.IJsonConverter
    {
        private readonly DefaultContractResolver contractResolver;

        public JsonNetSerializer()
        {
            contractResolver = new DefaultContractResolver
            {
                // KEY CONFIG !!!
                NamingStrategy = new CamelCaseNamingStrategy()
            };
        }

        /// <summary>Serialization of an object into JSON format.</summary>
        /// <param name="value">The object to serialize to JSON.</param>
        /// <param name="builder">Output destination.</param>
        /// <returns>Serialize succeeded (true/false)</returns>
        public bool SerializeObject(object value, StringBuilder builder)
        {
            try
            {
                string json = JsonConvert.SerializeObject(value, new JsonSerializerSettings
                {
                    ContractResolver = contractResolver
                });

                builder.Append(json);
            }
            catch (Exception e)
            {
                NLog.Common.InternalLogger.Error(e, "Error when custom JSON serialization");
                return false;
            }
            return true;
        }
    }
}

2)为新的自定义设置更改

var customConverter = new JsonNetSerializer();
ConfigurationItemFactory.Default.JsonConverter = customConverter;

使用它,将您的Json发送到NLog log.Info("Metadata: {@source}", metadata);