aspnetcore 使用serilog日志

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://www.cnblogs.com/morec/p/15912373.html

而在实际项目开发中,使用第三方日志框架来记录日志也是非常多的,首先一般基础的内置日志记录器在第三方日志框架中都有实现,然后很多第三方日志框架在功能上更强大和丰富,能满足我们更多的项目分析和诊断的需求。常用的有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)