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

How to force camel case in C# .NET structured logging?

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

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

假设一些 class 如下所示:

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 Whosebug question) .我猜记录器不会在后台使用。

如果对我有帮助,我正在使用我正在使用 .NET Core 2.2 和 v4.8.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);