前言
最近使用最新版的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>
复制代码
旧版本如下
2.Program代码如下
- 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();
- }
- }
- }
复制代码 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记载日志文件
这里为了方便测试代码,直接在WeatherForecastController(.Net Core创建WebAPI时的一个Controller)中使用
- 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),
- TemperatureC = Random.Shared.Next(-20, 55),
- Summary = Summaries[Random.Shared.Next(Summaries.Length)]
- })
- .ToArray();
- }
复制代码 5.结果
按日志级别,记载的内容就在这三个txt日志文件中
参考资料
https://www.cnblogs.com/zy-2015/p/15778002.html
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|