aspnetcore 使用serilog日誌

星仔007發表於2022-02-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
// https://github.com/serilog/serilog-aspnetcore#two-stage-initialization.
// General information about serilog can be found at
// https://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 https://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:
    // https://github.com/serilog/serilog/wiki/Provided-Sinks.
    "WriteTo": [
      {
        "Name": "Console"
      },
      {
        "Name": "File",
        "Args": { "path": "Logs/log.txt" }
      },
      {
        "Name": "Seq",
        "Args": { "serverUrl": "http://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)

相關文章