最近在写自己用的项目模版,使用到一个日志组件serilog,在nuget上看见下载量很高,就试用一下,还挺好用,记录一下。
涉及到的几个包:
Serilog:Serilog核心包
Serilog.AspNetCore:关于AspNetCore的扩展包,可以记录一些请求、路由信息
Serilog.Settings.Configuration:从 Microsoft.Extensions.Configuration 读取配置,包括appsettings.json
文件的配置
Serilog.Sinks.Console、Serilog.Sinks.MSSqlServer、Serilog.Sinks.File:带Sinks的就是日志输出的位置,Serilog实现了很多输出形式,我这里用到了控制台、文件和SqlServer数据库
安装、使用:
由于我平时写的是aspnetcore的web项目,这里就记录aspnetcore项目添加Serilog的方法
1、把用到的包装上:
Install-Package Serilog
Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.MSSqlServer
Install-Package Serilog.Sinks.Console
Install-Package Serilog.Sinks.File
PowerShell2、在程序入口Main初始化Loger:
// 默认logger
,默认输出到控制台,避免配置文件出错时logger初始化失败
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
try
{
Log.Information("应用程序启动");
var host = CreateHostBuilder(args).Build();
// 创建可用于解析作用域服务的新 Microsoft.Extensions.DependencyInjection.IServiceScope。
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
// 通过注入获取配置
var configuration = services.GetRequiredService<IConfiguration>();
// 从配置读取Logger配置
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
}
catch (Exception e)
{
Log.Error(e,$"读取配置时出错");
throw;
}
}
host.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "应用程序启动失败");
}
finally
{
Log.CloseAndFlush();
}
C#3、在CreateHostBuilder引用UseSerilog:
Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
C#4、在appsettings.json添加配置:
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"System": "Information",
"Microsoft": "Warning",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
"Serilog": {
"Using": [ "Serilog.Sinks.MSSqlServer" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"System": "Information",
"Microsoft": "Warning",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
}
},
{
"Name": "MSSqlServer",
"Args": {
"connectionString": "NamedConnectionString",
"sinkOptionsSection": {
"tableName": "Logs",
"schemaName": "EventLogging",
"autoCreateSqlTable": true,
"batchPostingLimit": 1000,
"period": "0.00:00:30"
},
"restrictedToMinimumLevel": "Warning"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"System": "Information",
"Microsoft": "Warning",
"Microsoft.AspNetCore.Hosting.Diagnostics": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <s:{SourceContext}>{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
},
JSON5、记日志:
可使用Serilog自带的静态类记日志
Log.Information("Hello, world!");
C#也可以通过注入方式获取Logger
private readonly ILogger<DbInitializer> logger;
public DbInitializer(ILogger<DbInitializer> logger)
{
this.scopeFactory = scopeFactory;
this.logger = logger;
}
public void Initialize()
{
logger.LogInformation("检查迁移开始");
using(var serviceScope = scopeFactory.CreateScope())
using(var context = serviceScope.ServiceProvider.GetService<MyDbContext>())
{
context.Database.Migrate();
}
logger.LogInformation("检查迁移结束");
}
C#