如何在Kafka中使用Serilog将日志序列化为JSON格式?
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

