【BlogBook书】6、Serilog:日志管理

2024-02-22 15:49:23 浏览数 (1)

框架高度集成Serilog,继承ASP.NETCore官方的ILogger<>接口,作为记录整个系统应用生命周期的日志工具,涵盖了平时企业应用的常见场景:

1、不同日志级别的记录;2、支持将日志输出到控制台;3、支持日志持久化到数据库;4、支持完整记录Sql执行日志;5、支持输出日志到文件;6、支持配置Seq日志中心;

一、相关的依赖注入配置

代码语言:javascript复制
builder.Host.AddSerilogSetup();


app.UseSerilogRequestLogging(options =>
{
    options.MessageTemplate = SerilogRequestUtility.HttpMessageTemplate;
    options.GetLevel = SerilogRequestUtility.GetRequestLevel;
    options.EnrichDiagnosticContext = SerilogRequestUtility.EnrichFromRequest;
});

相关参数设置

代码语言:javascript复制
"Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Information",
        "Microsoft.AspNetCore": "Warning",
        "System": "Warning",
        "System.Net.Http.HttpClient": "Warning",
        "Hangfire": "Information",
        "Magicodes": "Warning",
        "DotNetCore.CAP": "Information",
        "Savorboard.CAP": "Information",
        "Quartz": "Information"
      }
    }
  },

还有日志入库的数据库连接字符串配置

代码语言:javascript复制
"DBS": [  
    /*
      对应下边的 DBType
      MySql = 0,
      SqlServer = 1,
      Sqlite = 2,
      Oracle = 3,
      PostgreSQL = 4,
      Dm = 5,//达梦
      Kdbndp = 6,//人大金仓
    */    
    {
      "ConnId": "Log", //日志库连接固定名称,不要改,其他的可以改
      "DBType": 2,
      "Enabled": true,
      "HitRate": 50,
      "Connection": "WMBlogLog.db" //sqlite只写数据库名就行,可以替换其他数据库,并修改DBType即可
    },
]

还有一些配合其他功能(比如Aop、Sqlsugar等)的相关参数设置

代码语言:javascript复制
"AppSettings": {
    "LogToDb": true,
    "LogAOP": {
      "Enabled": false,
      "LogToFile": {
        "Enabled": true
      },
      "LogToDB": {
        "Enabled": true
      }
    },
    "UserAuditAOP": {
      "Enabled": false
    },
    "SqlAOP": {
      "Enabled": true,
      "LogToFile": {
        "Enabled": true
      },
      "LogToDB": {
        "Enabled": true
      },
      "LogToConsole": {
        "Enabled": true
      }
    }
  },

最后还有Seq平台相关配置

代码语言:javascript复制
"Seq": {
    "Enabled": true,
    "Address": "http://localhost:5341/",
    "ApiKey": ""
  }

二、使用方式

1、直接注入ILogger<>泛型接口即可

代码语言:javascript复制
private readonly ILogger<BlogController> _logger;

/// <summary>
/// 构造函数
/// </summary>
/// <param name="logger"></param>
/// 
public BlogController(ILogger<BlogController> logger)
{
    _logger = logger;
}


[HttpGet]
[Route("DetailNuxtNoPer")]
public async Task<MessageModel<BlogViewModels>> DetailNuxtNoPer(long id)
{
    _logger.LogInformation("xxxxxxxxxxxxxxxxxxx");
    return Success(await _blogArticleServices.GetBlogDetails(id));
}

2、或直接使用Serilog的Log类

代码语言:javascript复制
[HttpGet]
[Route("DetailNuxtNoPer")]
public async Task<MessageModel<BlogViewModels>> DetailNuxtNoPer(long id)
{
    Log.LogInformation("yyyyyyyyyyyyyyy");
    return Success(await _blogArticleServices.GetBlogDetails(id));
}

0 人点赞