You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Serilog采用驼峰命名策略解构JSON对象(替代默认大驼峰)

解决方案:给Serilog配置全局CamelCase解构策略

要让Serilog在解构对象时使用System.Text.Json的CamelCase命名策略,你可以通过自定义解构策略实现全局统一,无需逐个修改模型类。

步骤1:创建自定义解构策略类

实现Serilog的IDestructuringPolicy接口,复用和控制器一致的JSON序列化规则:

using Serilog.Core;
using Serilog.Events;
using System.Text.Json;

public class CamelCaseDestructuringPolicy : IDestructuringPolicy
{
    // 与控制器配置对齐的JSON序列化选项
    private static readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        // 可选:是否缩进日志中的JSON,按需调整
        WriteIndented = false
    };

    public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result)
    {
        // 让Serilog默认处理基本类型(数字、布尔)、字符串、枚举等,避免过度序列化
        if (value == null 
            || value.GetType().IsPrimitive 
            || value is string 
            || value.GetType().IsEnum)
        {
            result = null;
            return false;
        }

        // 将对象序列化为CamelCase格式的JSON字符串
        var camelCaseJson = JsonSerializer.Serialize(value, _jsonOptions);
        result = new ScalarValue(camelCaseJson);
        return true;
    }
}

步骤2:在Serilog配置中注册策略

在Program.cs的Serilog初始化代码中,添加自定义解构策略:

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog
builder.Host.UseSerilog((context, config) =>
{
    config
        .ReadFrom.Configuration(context.Configuration)
        // 注册自定义CamelCase解构策略
        .Destructure.With<CamelCaseDestructuringPolicy>()
        .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day);
});

// 保持原有的控制器JSON配置不变
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });

var app = builder.Build();

// ... 其他中间件配置

app.Run();

效果验证

当你在控制器中执行日志代码:

_logger.LogDebug("API RECEIVED {@InputModel}", input);

日志输出会变为:

API RECEIVED {"textField":"value"}

完全符合你期望的CamelCase格式。

补充说明

  • 该策略全局生效,所有非基本类型的对象解构都会遵循CamelCase规则,与控制器的JSON配置保持一致。
  • 如果需要对特定类型做特殊处理,可以在TryDestructure方法中添加类型判断,单独定制序列化逻辑。

内容的提问来源于stack exchange,提问作者albe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 19:15:09