介绍
本文写作年代比较久远,最新日志文档请查看:
.NET Core 和 ASP.NET Core 中的日志记录 | Microsoft Learn了解如何使用由 Microsoft Extension.Logging NuGet 包提供的日志记录框架。https://learn.microsoft.com/zh-cn/aspnet/core/fundamentals/logging/?view=aspnetcore-7.0
官方文档对日志部分洋洋洒洒与了一大堆,实际上对于应用程序,只要记住几个关键点就行了:
1、打开配置日志系统
2、选择提供程序
3、控制级别与分类
AspNetCore中自带了日志组件,不需要单独安装。
具体项目中,使用LoggerFactory,通过指定的ILoggerProvider来创建Logger对象。AspNetCore自带了四个ILoggerProvider的实现,分别是:
- Console
- Debug
- EventSource
- EventLog
不过,这四个都是针对Windows平台的,如果需要其他的实现,比如日志写入文本文件,就需要第三方的实现了,第三框架需要在Nuget中单独安装,具体安装步骤参考各个框架的文档。以下第三方的日志框架,可以直接链接到相应的项目网站查看文档:
- elmah.io (GitHub repo)
- Gelf (GitHub repo)
- JSNLog (GitHub repo)
- KissLog.net (GitHub repo)
- Log4Net (GitHub repo)
- Loggr (GitHub repo)
- NLog (GitHub repo)
- PLogger (GitHub repo)
- Sentry (GitHub repo)
- Serilog (GitHub repo)
- Stackdriver (Github repo)
配置
要在AspNetCore中启用日志,需要在Setup.cs文件中进行配置,通过扩展方法创建工厂实例,并注册到IOC容器中去。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddLogging(loggin=> {
loggin.AddConsole();
loggin.AddLog4Net();
});
}
这里同时还使用了Log4Net,所以还要在项目根目录下增加一个log4net.config文件:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="logs/app.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger: %message%newline %exception" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="DebugAppender" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
使用
因为IOC中注册了日志工厂实例,接下来就可以直接通过构造函数注入到相应的代码中,这里注入的方式有两种,两种注入方式的差别在于日志分类的方式不一样。
1、直接注入泛型ILogger<T>的实例,此时使用泛型参数作为日志分类:
public class HomeController : Controller
{
ILogger<HomeController> logger;
public HomeController(ILogger<HomeController> logger)
{
this.logger = logger;
}
public IActionResult Index()
{
logger.LogInformation("Hello World!");
return View();
}
}
2、注入工厂实例,再通过工厂得到非泛型ILogger的实例,此时使用给定的名称进行日志分类:
public class HomeController : Controller
{
ILogger logger;
public HomeController(ILoggerFactory factory)
{
this.logger = factory.CreateLogger("Home");
}
public IActionResult Index()
{
logger.LogInformation("Hello World!");
return View();
}
}
日志级别
日志组件提供了7个级别。
LogLevel | Value | Method | Description |
---|---|---|---|
Trace | 0 | LogTrace | Contain the most detailed messages. These messages may contain sensitive app data. These messages are disabled by default and should not be enabled in production. |
Debug | 1 | LogDebug | For debugging and development. Use with caution in production due to the high volume. |
Information | 2 | LogInformation | Tracks the general flow of the app. May have long-term value. |
Warning | 3 | LogWarning | For abnormal or unexpected events. Typically includes errors or conditions that don't cause the app to fail. |
Error | 4 | LogError | For errors and exceptions that cannot be handled. These messages indicate a failure in the current operation or request, not an app-wide failure. |
Critical | 5 | LogCritical | For failures that require immediate attention. Examples: data loss scenarios, out of disk space. |
None | 6 | Specifies that a logging category should not write any messages. |
在运行环境中使用哪个级别,需要在appsettings.json中配置:
{
"Logging": { // Default, all providers.
"LogLevel": {
"Microsoft": "Warning"
},
"Console": { // Console provider.
"LogLevel": {
"Microsoft": "Information"
}
}
}
}
过滤
日志组件提供了条件输出的功能,同样需要在Setup.cs的ConfigureServices方法中进行配置,比如:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddLogging(loggin=> {
loggin.AddConsole();
loggin.AddLog4Net();
loggin.AddFilter((provider, category, logLevel) =>
{
if (provider.Contains("ConsoleLoggerProvider")
&& category.Contains("Controller")
&& logLevel >= LogLevel.Information)
{
return true;
}
else if (provider.Contains("ConsoleLoggerProvider")
&& category.Contains("Microsoft")
&& logLevel >= LogLevel.Information)
{
return true;
}
else
{
return false;
}
});
});
}
附录:ASP.NET Core 和EF Core 中的日志分类
Category | Notes |
---|---|
Microsoft.AspNetCore | General ASP.NET Core diagnostics. |
Microsoft.AspNetCore.DataProtection | Which keys were considered, found, and used. |
Microsoft.AspNetCore.HostFiltering | Hosts allowed. |
Microsoft.AspNetCore.Hosting | How long HTTP requests took to complete and what time they started. Which hosting startup assemblies were loaded. |
Microsoft.AspNetCore.Mvc | MVC and Razor diagnostics. Model binding, filter execution, view compilation, action selection. |
Microsoft.AspNetCore.Routing | Route matching information. |
Microsoft.AspNetCore.Server | Connection start, stop, and keep alive responses. HTTPS certificate information. |
Microsoft.AspNetCore.StaticFiles | Files served. |
Microsoft.EntityFrameworkCore | General Entity Framework Core diagnostics. Database activity and configuration, change detection, migrations. |