前言
最近使用最新版的Serilog记录日志时,发现以前有些关于Serilog的Nuget弃用了,最关键的是有些配置写法也改变,于是就整理了一下最新版的Serilog配置方式(appsetting.json)的使用
说明:我是用的.Net6,最新长期支持版到.Net8了,不过Serilog我用的是最新版,配置方式都一样
1.安装Serilog相关Nuget包
新版Serilog相关Nuget
Serilog.AspNetCore
Serilog.Expressions
Serilog.Sinks.File
也可以把下面代码直接放入.csjproj工程项目文件中,把这三个包引用放进ItemGroup标签内,所需Nuget包会自动下载
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="Serilog.Expressions" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
本文项目使用.Net9.0:
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0" />
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
.NET6.0、.NET7.0、.NET8.0 Serilog版本如下:
较旧版本如下 :
2.Program代码如下
.NET6.0、.NET7.0、.NET8.0 Program.cs代码如下: 虽然使用.NET6.0 写法基本一致
using Serilog;
namespace WebAppNet6_Serilog
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
//使用Serilog
builder.Host.UseSerilog((context, logger) =>
{
//Serilog读取配置
logger.ReadFrom.Configuration(context.Configuration);
logger.Enrich.FromLogContext();
});
// 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.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
.NET 9.0 Program.cs代码:
using Serilog;
var builder = WebApplication.CreateBuilder(args);
//使用Serilog
builder.Host.UseSerilog((context, logger) =>
{
//Serilog读取配置
logger.ReadFrom.Configuration(context.Configuration);
logger.Enrich.FromLogContext();
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
3.配置文件(appsetting.json)代码如下
"Serilog": {
//"Using": [
// "Serilog.Sinks.RollingFile", //老版本的写入日志文件的Nuget包,现在已经弃用,请改用Serilog.Sinks.File
// "Serilog.Sinks.Console",
// "Serilog.Filters.Expressions" //老版本的日志过滤Nuget包,现在已经弃用,请改用Serilog.Expressions
//],
"Using": [ "Serilog.Sinks.File", "Serilog.Expressions" ],
"MinimumLevel": {
"Default": "Information", //最小记录日志级别
"Override": {
"Default": "Information",
"System": "Information",
"Microsoft": "Information"
}
},
"Enrich": [ "FromLogContext", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [{Level}] [{SourceContext}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l = 'Information'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/Info/log.txt",
"rollingInterval": "Day",
//"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} LogLevel:{Level} {Message:lj}{NewLine}{Exception}"
"outputTemplate": "【时间】{Timestamp:yyyy-MM-dd HH:mm:ss,fff}{NewLine}【等级】[{Level}]{NewLine}【消息】[{SourceContext}] {Message:lj}{NewLine}{Exception}{NewLine}"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l= 'Warning'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/Warn/log.txt",
"rollingInterval": "Day",
//"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} WARNING {ClassName}:0 - [{Version}] [{HttpRequestIP}] [{AppName}] {Message:lj}{NewLine}{Exception}"
//"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff}[{Level}]{HttpRequestId}{Message:lj}{NewLine}{Exception}{NewLine}"
"outputTemplate": "【时间】{Timestamp:yyyy-MM-dd HH:mm:ss,fff}{NewLine}【等级】[{Level}]{NewLine}【消息】[{SourceContext}] {Message:lj}{NewLine}{Exception}{NewLine}"
}
}
]
}
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "@l= 'Error'"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/Error/log.txt",
"rollingInterval": "Day",
//"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss,fff} ERROR {ClassName}:0 - [{Version}] [{HttpRequestIP}] [{AppName}] {Message:lj}{NewLine}{Exception}"
"outputTemplate": "【时间】{Timestamp:yyyy-MM-dd HH:mm:ss,fff}{NewLine}【等级】[{Level}]{NewLine}【消息】[{SourceContext}] {Message:lj}{NewLine}{Exception}{NewLine}"
}
}
]
}
}
}
]
}
4.依赖注入方式使用Serilog记录日志文件
.NET6.0、.NET7.0、.NET8.0 WeatherForecastController.cs代码如下:
private readonly ILogger<WeatherForecastController> _logger;
//注入日志
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
//记录日志
_logger.LogInformation("测试LogInformation");
_logger.LogWarning("测试LogWarning");
_logger.LogError("测试LogError");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),//如果这里报错,请看下面.NET9.0代码
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
.NET 9.0 SerilogController.cs代码:
[Route("api/[controller]")]
[ApiController]
public class SerilogController : ControllerBase
{
private readonly ILogger<SerilogController> _logger;
//注入日志
public SerilogController(ILogger<SerilogController> logger)
{
_logger = logger;
}
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet(Name = "SerilogTest")]
public IEnumerable<WeatherForecast> Get()
{
//记录日志
_logger.LogInformation("测试LogInformation");
_logger.LogWarning("测试LogWarning");
_logger.LogError("测试LogError");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.Parse(DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
调试运行后,复制下面启动后界面输出的地址到浏览器,打开即可:
在地址后面加:/api/serilog,看你控制器的配置
5.效果
按日志级别,记录的内容就在这三个txt日志文件中
参考文章:.Net Core(.Net6) 使用Serilog按日志等级写入日志,appsetting.json配置方式实现 - Misterj - 博客园
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。