前言

与许多其他 .NET 库一样,Serilog 为文件、控制台和其他位置提供诊断日志记录。它易于设置,具有干净的API,并且可以在最近的.NET平台之间移植。

与其他日志记录库不同,Serilog 在构建时考虑了强大的结构化事件数据。

官方配置文件样例:https://github.com/serilog/serilog-aspnetcore

日志组件 Serilog

NuGet 引入程序包

1
Serilog.AspNetCore

配置 Serilog

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using Serilog;
using Serilog.Events;

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
// Add this line:
.WriteTo.File(
@"myapp.txt",
fileSizeLimitBytes: 1_000_000,
rollOnFileSizeLimit: true,
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(1))
.CreateLogger();

try
{
Log.Information("Starting web host");

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddLogging();

builder.Host.UseSerilog(dispose: true); // <-- 不要漏了

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}

app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = "";
});

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
//throw;
}
finally
{
Log.CloseAndFlush();
}

开始使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
_logger.LogInformation($"{this.GetType().Name} 被构造了!");
}

public IActionResult Index()
{

try
{
List<string> list = null;
list.Add("a");
}
catch (Exception ex)
{
_logger.LogError(ex, "Index 执行报错了!");
}

_logger.LogInformation($"Index 被执行了!");
return View();
}
}