.Net 6.0 .Net7.0 .Net8.0 .Net9.0 使用 Serilog 按日志等级写入日志及 appsetting.json 配置方式实现

前言

最近使用最新版的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 - 博客园

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
csdn_aspnet12 天前
.NET 9.0 WebApi 发布到 IIS 详细步骤
iis·.net9.0
csdn_aspnet22 天前
使用 .NET 6 或 .NET 8 上传大文件
.net6.0·.net8.0
csdn_aspnet1 个月前
.NET 6.0 中接入 Log4net 和 NLog
log4net·nlog·.net6.0
csdn_aspnet1 个月前
.NET 9 已发布,您可以这样升级或更新
.net9.0
csdn_aspnet1 个月前
在 .NET 9 中让您的 OpenAPI(Swagger)文档 UI 变得出色
ui·.net9.0
csdn_aspnet1 个月前
在.NET 6中使用Serilog收集日志
webapi·.net6.0
IT规划师3 个月前
Serilog文档翻译系列(八) - 记录器的生命周期、可靠性
c#·日志·.net core·serilog·.netcore日志
IT规划师3 个月前
Serilog文档翻译系列(七) - 应用设置、调试和诊断、开发接收器
日志·.net core·serilog
IT规划师4 个月前
Serilog文档翻译系列(六) - 可用的接收器、增强器、格式化输出
日志·.net core·serilog