本文主要介绍在ASP.NET Core中使用两种日志组件
- Logging:Flexible & free open-source logging for .NET
- Log4Net: Apache log4net框架在Microsoft .NET平台的实现
一 使用ASP.NET Core本身自带了轻量级的日志记录日志框架Logging
appsettings.json中对Logging的配置:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
Logging的使用
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogError("logger记录错误");
return View();
}
}
错误将打印在控制台
二使用第三方日志组件(再此使用Log4Net)
ASP.NET Core 2.0已经可以使用Log4Net,安装Nuget包,我安装的是log4net 2.08
log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section contains the log4net configuration settings -->
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\AT" />
<!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
<datePattern value="_yyyyMMdd'.log'" />
<!--是否追加到文件,默认为true,通常无需设置-->
<appendToFile value="true" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<!--StaticLogFileName的值如果为true,则当前日志文件(相对于历史日志文件而言)的文件名只取File参数。如果为false,则文件名取File+DatePattern。-->
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
<param name="Header" value=" ----------------------Header-------------------------
" />
<param name="Footer" value=" ----------------------footer--------------------------
" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
修改启动类
public static ILoggerRepository Repository;//log4net
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Repository = LogManager.CreateRepository("NETCoreRepository");
XmlConfigurator.Configure(Repository, new FileInfo("log4net.config"));
}
在控制器中调用Log4Net
private ILog log = LogManager.GetLogger(Startup.Repository.Name, typeof(HomeController));
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogError("logger记录错误");
log.Error("log4net记录错误");
return View();
}