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

如何在Kafka中使用Serilog将日志序列化为JSON格式?

Solution

To log objects as nested JSON structures instead of string representations in Serilog.Sinks.ConfluentKafka, follow these steps:

1. Use the @ Operator in the Message Template

Modify your log statement to include the @ symbol before the property name. This tells Serilog to serialize the object as a structured property rather than converting it to a string:

var message = new Message { Name = "x", Age = 1};
logger.LogInformation("{@Message}", message);

2. Ensure JSON Formatter is Configured

Make sure your Serilog configuration uses a JSON formatter that supports structured properties. This is typically set up when configuring the Kafka sink:

Log.Logger = new LoggerConfiguration()
    .WriteTo.ConfluentKafka(
        bootstrapServers: "your-kafka-broker:9092",
        topic: "logs-topic",
        formatter: new JsonFormatter() // Ensures structured JSON output
    )
    .CreateLogger();

3. Verify Object Properties are Public

Ensure the Message class has public properties that Serilog can serialize. Private or internal properties won't be included in the nested structure:

public class Message
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Result

After making these changes, your log output will look like this:

{
  "Timestamp": "2024-05-20T12:34:56.789Z",
  "Level": "Information",
  "Properties": {
     "Message": { 
         "Name": "x", 
         "Age": 1 
     }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 19:52:38