net6 使用Serilog.Sinks.RabbitMQ
- User
net6 使用Serilog.Sinks.RabbitMQ
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
net6 使用Serilog.Sinks.RabbitMQ
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
在 .NET 6 中使用 Serilog.Sinks.RabbitMQ 可以将日志事件通过 RabbitMQ 发送到消息队列,供其他服务消费。以下是详细步骤和示例代码:
首先安装以下 NuGet 包:
dotnet add package Serilog
dotnet add package Serilog.Sinks.RabbitMQ
在 Program.cs 中配置 Serilog,指定 RabbitMQ Sink:
using Serilog;
using Serilog.Formatting.Json;
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.RabbitMQ(
rabbitMQConfiguration: new Serilog.Sinks.RabbitMQ.Sinks.RabbitMQ.RabbitMQConfiguration
{
Hostname = "localhost", // RabbitMQ 服务器地址
Port = 5672, // 默认端口
Username = "guest", // 用户名
Password = "guest", // 密码
Exchange = "logs-exchange", // Exchange 名称
ExchangeType = "direct", // Exchange 类型(direct/topic/fanout)
RouteKey = "log-events", // 路由键
DeliveryMode = RabbitMQDeliveryMode.Durable, // 持久化消息
AutoCreateExchange = true // 自动创建 Exchange
},
formatter: new JsonFormatter() // 日志格式(JSON)
)
.CreateLogger();
try
{
Log.Information("Starting application...");
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog(); // 启用 Serilog
// 其他服务配置...
var app = builder.Build();
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
Log.CloseAndFlush();
}
在 appsettings.json 中添加 Serilog 配置,增强灵活性:
{
"Serilog": {
"Using": ["Serilog.Sinks.RabbitMQ"],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "RabbitMQ",
"Args": {
"hostname": "localhost",
"port": 5672,
"username": "guest",
"password": "guest",
"exchange": "logs-exchange",
"exchangeType": "direct",
"routeKey": "log-events",
"deliveryMode": "Durable",
"autoCreateExchange": true
}
}
]
}
}
在代码中记录日志:
Log.Information("This is an info message");
Log.Error("This is an error message");
通过 RabbitMQ Management UI 或其他消费者检查日志是否正确发送:
http://localhost:15672(默认管理界面)logs-exchange 是否有绑定的队列和消息。连接失败
5672(或 5671 如果使用 TLS)。Exchange 未创建
AutoCreateExchange = true 或手动创建 Exchange。权限问题
通过以上步骤,即可在 .NET 6 中将 Serilog 日志发送到 RabbitMQ。如果需要更高级的配置(如 TLS、自定义路由),请参考 Serilog.Sinks.RabbitMQ 文档。