asp.net core web api中Serilog的使用

391 阅读1分钟

第一步、引入包

dotnet add package Serilog.AspNetCore

第二步、修改Program.cs

using Serilog;
using Serilog.Events;
using Serilog.Formatting.Compact;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    // 这个是过滤一些不想看到的日志
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    // Filter out ASP.NET Core infrastructre logs that are Information and below
    .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    // 用json格式输入到json文件中
    .WriteTo.File(new RenderedCompactJsonFormatter(),"log-.json", rollingInterval: RollingInterval.Day)
    .CreateLogger();

Log.Information("日志");

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// 这条是必须添加
builder.Host.UseSerilog();
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();
}

// 这个会多出一条记录出来,HTTP GET /WeatherForecast responded 200 in 16.2895 ms
app.UseSerilogRequestLogging();

app.UseAuthorization();

app.MapControllers();

app.Run();

第三步、控制器中使用

using Microsoft.AspNetCore.Mvc;

namespace testerilog11.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public void Get()
        {
            _logger.LogInformation("日志信息");
        }
    }
}

Json输出格式为

image.png

Console输出格式为

image.png