我试图在我的 asp.net core 项目中使用 Serilog 将某些类型的日志记录到不同的接收器,具体取决于正在记录的内容,但我最终得到的是 2 个具有完全相同内容的独立日志。 我想配置记录器,以便如果类型是“天气日志”,它会记录到天气日志文件,否则它会记录到 nin 日志文件。我安装了 serilog.aspnetcore 和表达式
这是我的代码和配置:
using Microsoft.AspNetCore.Mvc;
using Serilog;
namespace LoggerTest.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private static readonly string[] nins = new[]
{
"1", "2", "3", "4", "6", "7", "8", "9", "10", "11"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
_logger.LogInformation("WeatherForecast controller called ");
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
var type = "Weather logs";
var result = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)],
})
.ToArray();
_logger.LogInformation("Weather logs: Informantion obtained is {@Result}", result);
type = "Nin logs";
var test = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = nins[Random.Shared.Next(Summaries.Length)],
})
.ToArray();
_logger.LogInformation("{@Type}: Informantion obtained is {@Test}", type, test[0]);
return result;
}
}
}
我的program.cs文件:
using Serilog;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Host.UseSerilog((context, configuration) =>
configuration.ReadFrom.Configuration(context.Configuration));
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseSerilogRequestLogging();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
我的appsettings.json:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "logs/weather-.json",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
},
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@m like 'Weather logs%'"
}
}
]
},
{
"Name": "File",
"Args": {
"path": "logs/nin-.json",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
},
"AllowedHosts": "*"
}
两个日志文件包含相同的信息:
{"@t":"2024-04-01T20:59:11.4950381Z","@mt":"WeatherForecast controller called ","@tr":"4d934bc9bfd6378d3aa8837a233c28ea","@sp":"0b9630cf3e5ed876","SourceContext":"LoggerTest.Controllers.WeatherForecastController","ActionId":"4282424a-3da7-492f-8959-e11bf53f34aa","ActionName":"LoggerTest.Controllers.WeatherForecastController.Get (LoggerTest)","RequestId":"0HN2IHQ4JSE88:00000009","RequestPath":"/WeatherForecast","ConnectionId":"0HN2IHQ4JSE88"}
{"@t":"2024-04-01T20:59:11.5670441Z","@mt":"{@Type}: Weather logs: Informantion obtained is {@Result}","@tr":"4d934bc9bfd6378d3aa8837a233c28ea","@sp":"0b9630cf3e5ed876","Type":"Weather logs","Result":[{"Date":"2024-04-02","TemperatureC":7,"TemperatureF":44,"Summary":"Hot","Type":null,"$type":"WeatherForecast"},{"Date":"2024-04-03","TemperatureC":8,"TemperatureF":46,"Summary":"Chilly","Type":null,"$type":"WeatherForecast"},{"Date":"2024-04-04","TemperatureC":25,"TemperatureF":76,"Summary":"Mild","Type":null,"$type":"WeatherForecast"},{"Date":"2024-04-05","TemperatureC":-16,"TemperatureF":4,"Summary":"Bracing","Type":null,"$type":"WeatherForecast"},{"Date":"2024-04-06","TemperatureC":37,"TemperatureF":98,"Summary":"Sweltering","Type":null,"$type":"WeatherForecast"}],"SourceContext":"LoggerTest.Controllers.WeatherForecastController","ActionId":"4282424a-3da7-492f-8959-e11bf53f34aa","ActionName":"LoggerTest.Controllers.WeatherForecastController.Get (LoggerTest)","RequestId":"0HN2IHQ4JSE88:00000009","RequestPath":"/WeatherForecast","ConnectionId":"0HN2IHQ4JSE88"}
{"@t":"2024-04-01T20:59:11.5855717Z","@mt":"{@Type}: Informantion obtained is {@Test}","@tr":"4d934bc9bfd6378d3aa8837a233c28ea","@sp":"0b9630cf3e5ed876","Type":"Nin logs","Test":{"Date":"2024-04-02","TemperatureC":9,"TemperatureF":48,"Summary":"11","Type":null,"$type":"WeatherForecast"},"SourceContext":"LoggerTest.Controllers.WeatherForecastController","ActionId":"4282424a-3da7-492f-8959-e11bf53f34aa","ActionName":"LoggerTest.Controllers.WeatherForecastController.Get (LoggerTest)","RequestId":"0HN2IHQ4JSE88:00000009","RequestPath":"/WeatherForecast","ConnectionId":"0HN2IHQ4JSE88"}
{"@t":"2024-04-01T20:59:11.6216513Z","@mt":"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms","@r":["184.2060"],"@tr":"4d934bc9bfd6378d3aa8837a233c28ea","@sp":"0b9630cf3e5ed876","RequestMethod":"GET","RequestPath":"/WeatherForecast","StatusCode":200,"Elapsed":184.206,"SourceContext":"Serilog.AspNetCore.RequestLoggingMiddleware","RequestId":"0HN2IHQ4JSE88:00000009","ConnectionId":"0HN2IHQ4JSE88"}
问题似乎出在 Serilog 过滤器的配置上。您正在使用 ByInclusionOnly 过滤器,但它没有按预期工作。相反,您可以将 ByInclusion 过滤器与指定要过滤的日志事件属性的表达式一起使用。
{
"Serilog": {
"Using": ["Serilog.Sinks.Console", "Serilog.Sinks.File"],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "logs/weather-.json",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
},
"Filter": [
{
"Name": "ByIncluding",
"Args": {
"expression": "Contains(@m, 'Weather logs')"
}
}
]
},
{
"Name": "File",
"Args": {
"path": "logs/nin-.json",
"rollingInterval": "Day",
"rollOnFileSizeLimit": true,
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
},
"Filter": [
{
"Name": "ByIncluding",
"Args": {
"expression": "!Contains(@m, 'Weather logs')"
}
}
]
}
],
"Enrich": ["FromLogContext", "WithMachineName", "WithThreadId"]
},
"AllowedHosts": "*"
}
确保您安装了 Serilog.Filters.Expressions 包才能正常工作。您可以使用 NuGet 安装它:
dotnet add package Serilog.Filters.Expressions
通过此配置,包含“天气日志”的日志将写入logs/weather-.json,其他日志将写入logs/nin-.json。