原文链接:https://blog.csdn.net/kevin860/article/details/106881062
1.引用包:
Log4Net
Microsoft.Extensions.Logging.Log4Net.AspNetCore
Microsoft.Extensions.Logging
//loggingbuilder.AddFilter该方法需要引入Microsoft.Extensions.Logging名称空间
loggingbuilder.AddFilter("System", LogLevel.Warning); //过滤掉系统默认的一些日志
loggingbuilder.AddFilter("Microsoft", LogLevel.Warning);//过滤掉系统默认的一些日志
2.导入Log4net.config 配置文件
<?xml version="1.0" encoding="utf-8"?>
<log4net>
<appender name="RollingAppender" type="log4net.Appender.RollingFileAppender">
<!--指定日志文件保存的目录-->
<file value="log\log.txt"/>
<!--追加日志内容-->
<appendToFile value="true"/>
<!--可以为:Once|Size|Date|Composite-->
<!--Compoosite为Size和Date的组合-->
<rollingStyle value="Composite"/>
<!--设置为true,当前最新日志文件名永远为file字节中的名字-->
<staticLogFileName value="false"/>
<!--当备份文件时,备份文件的名称及后缀名-->
<datePattern value="yyyyMMdd.TXT"/>
<!--日志最大个数-->
<!--rollingStyle节点为Size时,只能有value个日志-->
<!--rollingStyle节点为Composie时,每天有value个日志-->
<maxSizeRollBackups value="20"/>
<!--可用的单位:KB|MB|GB-->
<maximumFileSize value="5MB"/>
<filter type="log4net.Filter.LevelRangeFilter">
<param name="LevelMin" value="ALL"/>
<param name="LevelMax" value="FATAL"/>
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<priority value="ALL"/>
<level value="ALL"/>
<appender-ref ref="RollingAppender"/>
</root>
</log4net>
3.注册到program中
builder.Logging.AddFilter("System", LogLevel.Warning); //过滤掉系统默认的一些日志
builder.Logging.AddFilter("Microsoft", LogLevel.Warning); //过滤掉系统默认的一些日志
builder.Logging.AddLog4Net("Config/Log4net.config");
4.Controller中使用
private readonly ILogger<WeatherForecastController> _logger;
private readonly ILoggerFactory _loggerFactory;
public WeatherForecastController(ILogger<WeatherForecastController> logger, ILoggerFactory loggerFactory)
{
_logger = logger;
_logger.LogInformation($"1..构造函数中!{DateTime.Now}");
_loggerFactory = loggerFactory;
ILogger<WeatherForecastController> logger2 = this._loggerFactory.CreateLogger<WeatherForecastController>();
logger2.LogInformation($"2..{this.GetType().Name}被logger2中构造了。。。");
}