Skip to content
On this page

Serilog

Serilog — simple .NET logging with fully-structured events

主要是想使用结构化日志信息

powershell
NuGet\Install-Package Serilog.AspNetCore -Version 6.1.0

NuGet\Install-Package Serilog.Exceptions -Version 8.4.0

NuGet\Install-Package Serilog.Enrichers.Environment -Version 2.2.0
NuGet\Install-Package Serilog.Enrichers.Process -Version 2.0.2
NuGet\Install-Package Serilog.Enrichers.Thread -Version 3.2.0-dev-00752

NuGet\Install-Package Serilog.Sinks.Async -Version 1.5.0
项目结构
Host
	Configurations
		logger.json			# 日志配置
		Startup.cs			# 添加对logger.json文件的读取
	Porgram.cs
Infrastructure
	Logging
		LoggerSettings.cs	# 用于映射Logger.json配置
		Startup.cs			# serilog日志配置
		StaticLogger.cs		# 用于Program中 在Serilog配置未生效前使用基础的Serilog配置

Host/Program.cs

c#
using Serilog;
using YSKM.WebApi.Host.Configurations;
using YSKM.WebApi.Infrastructure.Logging;

StaticLogger.EnsureInitialized();
Log.Information("Server Booting Up...");
try
{
    var builder = WebApplication.CreateBuilder(args);
    
    builder.AddConfigurations();
    builder.Services.AddControllers();

    var app = builder.Build();

    app.UseHttpsRedirection();

    app.MapControllers();

    app.Run();
}
catch (Exception ex)
{
    StaticLogger.EnsureInitialized();
    Log.Fatal(ex, "Unhandled exception");
}
finally
{
    StaticLogger.EnsureInitialized();
    Log.Information("Server Shutting down...");
    Log.CloseAndFlush();
}

在项目启动入口外 最好包一层try catch

处理运行中未能处理的异常 严谨🐶

这也是为啥要弄个StaticLogger 因为此时程序还没启动 还没有注入相应的Log