.NetCore 中Log4net简单使用
1. 添加log4net配置文件
如图所示,在项目中添加log4net.config配置文件:
log4net.config配置文件内容如下,文件属性设置为始终复制:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
</configSections>
<appSettings>
</appSettings>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<!--File Appender-->
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file value="bin\Debug\netcoreapp3.1\Log4Net\" />
<rollingStyle value="Composite" />
<datePattern value="yyyy-MM-dd".log"" />
<staticLogFileName value="false" />
<param name="Encoding" value="utf-8" />
<maximumFileSize value="100MB" />
<countDirection value="0" />
<maxSizeRollBackups value="100" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="记录时间:%date 线程:[%thread] 日志级别:%-5level 记录类:%logger 日志消息:%message%newline" />
</layout>
</appender>
<!--Console appender-->
<appender name="console" type="log4net.Appender.ManagedColoredConsoleAppender">
<mapping>
<level value="INFO" />
<forecolor value="Green" />
</mapping>
<mapping>
<level value="WARN" />
<forecolor value="Yellow" />
</mapping>
<mapping>
<level value="ERROR" />
<forecolor value="Red" />
</mapping>
<mapping>
<level value="DEBUG" />
<forecolor value="Blue" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionpattern value="记录时间:%date 线程:[%thread] 日志级别:%-5level 记录类:%logger 日志消息:%message%newline" />
</layout>
</appender>
</log4net>
</configuration>
2. 读取 log4net.config 文件配置
帮助类库中添加一个LogHelper类:
需要引入的库:log4net,通过Nuget包添加
LogHelper内容如下:
public static class LogHelper
{
/// 使用log4net配置
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseLog4net(this IApplicationBuilder app)
{
//var dir = Assembly.GetEntryAssembly() + "Log4Net";
var logRepository = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
return app;
}
}
3. 注册log4Net服务
在startup.cs文件的Configure方法中添加:
app.UseLog4net();
引入LogHelper的命名空间
4. 记录日志
private readonly ILog log = LogManager.GetLogger(typeof(StudentsController));
log.Debug("Something!!!");
配置的日志输出目录为:==bin\Debug\netcoreapp3.1\Log4Net==,可以到此目录查看日志。
5. 更多
查看更多的功能:
log4net更多功能
来源:CSDN
作者:佛陀爱老虎
链接:https://blog.csdn.net/m0_37591671/article/details/80197458