C# .NET6 Serilog的配置和使用

入口文件:Program.cs

using Serilog;
using Serilog.Events;

// 创建Serilog
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateBootstrapLogger();
try
{
    Log.Information("Starting web host");

    // 创建应用程序
    var builder = WebApplication.CreateBuilder(args);
    // 配置文件
    var configuration = builder.Configuration;
    // 配置Serilog
    builder.Host.UseSerilog((context, services, configuration) => configuration
                    .ReadFrom.Configuration(context.Configuration)
                    .ReadFrom.Services(services));

    // 向容器中添加服务。
    // 添加控制器
    builder.Services.AddControllers();
    // 添加ApiExplorer
    builder.Services.AddEndpointsApiExplorer();
    // 添加Swagger
    builder.Services.AddSwaggerGen();
    // 生成应用程序
    var app = builder.Build();

    // 配置HTTP请求管道。
    // 开发者模式
    if (app.Environment.IsDevelopment())
    {
        // 使用开发者异常页面 
        app.UseDeveloperExceptionPage();
    }
    // 使用Swagger
    app.UseSwagger();
    app.UseSwaggerUI();
    // 使用Serilog记录Request
    app.UseSerilogRequestLogging();
    // 使用HTTPS重定向
    app.UseHttpsRedirection();
    // 使用身份认证
    app.UseAuthorization();
    // 使用控制器
    app.MapControllers();
    // 运行应用程序
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush();
}

配置文件:appsettings.json

{
  "AllowedHosts": "*",
  "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "Microsoft.AspNetCore": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "Path": "D:/logs/WebApi_NET6.0/log-.txt",
          "RollingInterval": "Day",
          "OutputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{RequestId}][{Level:u3}][{SourceContext}] {Message:lj}{NewLine}{Exception}",
          "Shared": true,
          "RollOnFileSizeLimit": true,
          "FileSizeLimitBytes": 1048576,
          "RetainedFileCountLimit": 1000
        }
      },
      {
        "Name": "Console",
        "Args": {}
      },
      {
        "Name": "Debug",
        "Args": {}
      }
    ]
  }
}

 

posted @ 2023-01-16 14:35  Mr_Xul  阅读(4172)  评论(2编辑  收藏  举报