ASP.Net Core整合Serilog简易入门
官方文档:https://serilog.net/
PM> Install-Package Serilog
PM> Install-Package Serilog.Sinks.Console #输出到控制台
PM> Install-Package Serilog.Sinks.File #输出到本地文件
nuget下载这几个包
在Program的Main方法中配置Serilog,这里选择直接输出本地文件
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build())
.WriteTo.File(Path.Combine("logs", "log"), rollingInterval: RollingInterval.Minute) //日志生成路径,项目根目录logs文件夹, rollingInterval: RollingInterval.Minute 每分钟生成一次
.CreateLogger();
CreateHostBuilder(args).Build().Run();
}
//CreateHostBuilder方法中添加UseSerilog()
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseSerilog(); //添加UseSerilog()
在appsettings.json文件中把原来的log配置删除,添加Serilog配置。
输出格式可参考官方文档Configuration Basics
{
"Serilog": {
// 日志输出级别
"MinimumLevel": {
"Default": "Information",
"Override": {
// 日志调用类命名空间如果以 Microsoft 开头,覆盖日志输出最小级别为 Information
"Microsoft": "Information",
"System": "Information", //简化日志
"Microsoft.AspNetCore": "Information"
}
}
},
"AllowedHosts": "*"
}
在Controller里构造函数注入,直接使用ILogger
private readonly ILogger<HomeController> log;
public HomeController(ILogger<HomeController> logger)
{
log = logger ?? throw new ArgumentException(nameof(logger));
}
[HttpGet]
public ActionResult<string> Get()
{
log.LogInformation("Hello AsUu.");
log.LogError("Goodbye AsUu");
//记录
return "AsUu";
}
运行之后生成该分钟内的日志文件


Serilog日志的级别(Level)
| Level | Usage |
|---|---|
Verbose |
Verbose is the noisiest level, rarely (if ever) enabled for a production app. |
Debug |
Debug is used for internal system events that are not necessarily observable from the outside, but useful when determining how something happened. |
Information |
Information events describe things happening in the system that correspond to its responsibilities and functions. Generally these are the observable actions the system can perform. |
Warning |
When service is degraded, endangered, or may be behaving outside of its expected parameters, Warning level events are used. |
Error |
When functionality is unavailable or expectations broken, an Error event is used. |
Fatal |
The most critical level, Fatal events demand immediate attention. |
当然也有其他方法,这里只列举了这一种。Serilog是十分成熟、灵活和功能强大的日志框架,Serilog的输出对象称为sink(水槽),在社区中提供了大量的开源的sinks,如MongoDb,RabbitMQ,PostgreSQL等等。

浙公网安备 33010602011771号