前置:为项目安装如下两个依赖
1.创建文件夹cfgFile
2.创建log4net.Config
cs
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<!--文件地址-->
<file value="logs/log-file.txt" />
<!--追加日志内容-->
<appendToFile value="true" />
<!--多线程-->
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs/LogFile/Error/" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd'.log'" />
<maxSizeRollBackups value="20" />
<maximumFileSize value="3MB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
</appender>
<appender name="WarnRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs/LogFile/Warn/" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd'.log'" />
<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="logs/LogFile/Info/" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd'.log'" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread %-5level] %n %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="INFO" />
</filter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
<appender-ref ref="RollingLogFileAppender" />
<appender-ref ref="WarnRollingFileAppender" />
<appender-ref ref="InfoRollingFileAppender" />
</root>
</log4net>
3.使用日志
Program.cs->添加配置
cs
//日志
builder.Logging.AddLog4Net("CfgFile/log4net.Config");
配置位置tips:
4.通过构造函数注入日志在控制器中
cs
//UsersController控制器中
private readonly ILogger<UsersController> _logger;
public UsersController(ILogger<UsersController> logger)
{
_logger = logger;
}
配置位置tips:
5.使用日志
cs
_logger.LogInformation("这是一个Get请求");
配置位置tips:
6.测试日志是否成功
执行项目
- 查看bin文件夹下是否多了下面的目录
- 调用Get命令,查看在输出中是否有刚才那段日志