aspnetcore 使用serilog日誌

  • 2022 年 2 月 19 日
  • 筆記
而在實際項目開發中,使用第三方日誌框架來記錄日誌也是非常多的,首先一般基礎的內置日誌記錄器在第三方日誌框架中都有實現,然後很多第三方日誌框架在功能上更強大和豐富,能滿足我們更多的項目分析和診斷的需求。常用的有log4net,更複雜的elk,項目中有用到exceptionless。下面說的是serilog:

首先建個aspnetcorewebapi6.0的項目

安裝組件:

Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)

using Serilog;
using Serilog.Events;

// Setup serilog in a two-step process. First, we configure basic logging
// to be able to log errors during ASP.NET Core startup. Later, we read
// log settings from appsettings.json. Read more at
// //github.com/serilog/serilog-aspnetcore#two-stage-initialization.
// General information about serilog can be found at
// //serilog.net/
Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateBootstrapLogger();

try
{
    Log.Information("Starting the web host");
    var builder = WebApplication.CreateBuilder(args);
    // Full setup of serilog. We read log settings from appsettings.json
    builder.Host.UseSerilog((context, services, configuration) => configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext());
    // Add services to the container.

    builder.Services.AddControllers();
    // Learn more about configuring Swagger/OpenAPI at //aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    var app = builder.Build();

    // Configure the HTTP request pipeline.
    app.UseSerilogRequestLogging(configure =>
    {
        configure.MessageTemplate = "HTTP {RequestMethod} {RequestPath} ({UserId}) responded {StatusCode} in {Elapsed:0.0000}ms";
    });
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }

    app.UseHttpsRedirection();

    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}
catch
(Exception ex)
{
    Log.Fatal(ex, "Host terminated unexpexctedly");
}
finally
{
    Log.CloseAndFlush();
}
{
  //"Logging": {
  //  "LogLevel": {
  //    "Default": "Information",
  //    "Microsoft.AspNetCore": "Warning"
  //  }
  //},
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ],
    "MinimumLevel": "Information",
    // Where do we want to write our logs to? Choose from a large number of sinks:
    // //github.com/serilog/serilog/wiki/Provided-Sinks.
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": { "path": "Logs/log.txt" }
      },
      {
        "Name": "Seq",
        "Args": { "serverUrl": "//localhost:8888" }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "AspNetCoreSerilogDemo"
    }
  },
  "AllowedHosts": "*"
}

運行結果如下,已替換系統自帶information:

 

請求跟蹤分析:

using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreSerilogDemo.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SeriLogDemoController : ControllerBase
    {
       

        private readonly ILogger<SeriLogDemoController> _logger;

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

        [HttpGet]
        public string String()
        {
            _logger.LogInformation("this is serilog...");
            return "Suscess";
        }
     
    }
}

 配置文件裡面輸出路徑有"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File", "Serilog.Sinks.Seq" ],所以同樣會輸出到日誌文件中,指定路徑和文件名:

 

更多更詳細功能參考:

Serilog — simple .NET logging with fully-structured events

Seq — centralized structured logs for .NET, Java, Node.js (datalust.co)

示例程式碼:

exercise/AspNetCoreSerilogDemo at master · liuzhixin405/exercise (github.com)

Tags: