NetCore使用Log4Net记录日志
Core使用Log4Net输出日志
-
1.创建Core项目
-
2.用Nuget下载引用log4net 和 Microsoft.Extensions.Logging.Log4Net.AspNetCore 文件
-
3.添加log4net.Config配置文件
在工程目录下添加log4net.config配置文件
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<root>
<level value="All" />
<appender-ref ref="ErrorRollingFileAppender" />
<appender-ref ref="WarnRollingFileAppender" />
<appender-ref ref="InfoRollingFileAppender" />
</root>
<appender name="ErrorRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/Error/" />
<appendToFile value="true" />
<rollingStyle value="Date"/>
<datePattern value="yyyy-MM-dd-'error.log'"/>
<maxSizeRollBackups value="100" />
<staticLogFileName value="false" />
<encoding value="utf-8" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread %-5level] %n -- %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
</appender>
<appender name="WarnRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/Warn/" />
<appendToFile value="true" />
<rollingStyle value="Date"/>
<datePattern value="yyyy-MM-dd-'warn.log'"/>
<maxSizeRollBackups value="100" />
<staticLogFileName value="false" />
<encoding value="utf-8" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread %-5level] %n -- %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN" />
<levelMax value="WARN" />
</filter>
</appender>
<appender name="InfoRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/Info/" />
<appendToFile value="true" />
<rollingStyle value="Date"/>
<datePattern value="yyyy-MM-dd-'info.log'"/>
<maxSizeRollBackups value="100" />
<staticLogFileName value="false" />
<encoding value="utf-8" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread %-5level] %n -- %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="TRACE" />
<levelMax value="INFO" />
</filter>
</appender>
</log4net>
-
4.Core启用Log4Net
在Program.cs文件里的CreateHostBuilder函数中启用Log4Net 示例代码:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddLog4Net();//启用Log4Net
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
-
5.记录日志
- 创建Logger (Logger为ILoggerFactory类型注入)
_logger = logger.CreateLogger<XController>();
或者
_logger = logger.CreateLogger("记录日志");
- 输出日志
_logger.LogInformation("输出日志信息");
如果说,岁月是一首歌,那么我们便是歌者,纵使孤独,仍会固执高歌;如果说,岁月是一段旅程,那么我们便是行者,且行且梦,让生命丰盈。