.netcore入门20:aspnetcore集成log4net
程序员文章站
2024-01-29 18:08:10
...
环境:
- window 10
- vs2019 16.5.1
- asp.net core 3.1
- Microsoft.Extensions.Logging.Log4Net.AspNetCore 3.1.0
参照:
Apache log4net™ Manual - Configuration
Microsoft.Extensions.Logging.Log4Net.AspNetCore 地址
一、准备aspnetcore webapi项目
新建一个webapi项目即可,略。
二、安装nuget包
三、在Programe.cs文件中配置log4net
四、在项目目录下新建log4net.config文件
log4net.config文件内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<!--vs调试窗口输出-->
<appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger scope=[%property{scope}] - %message %exception%newline" />
</layout>
</appender>
<!--以滚动文件的方式输出)-->
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<!--日志路径-->
<file value="Log/" />
<!--是否是向文件中追加日志-->
<appendToFile value="true" />
<!--log保留天数-->
<param name= "MaxSizeRollBackups" value= "10"/>
<!--每个文件最大1M-->
<param name="maximumFileSize" value="1MB" />
<!--日志根据日期滚动-->
<param name="RollingStyle" value="Date" />
<!--日志文件名格式为:logs_20080831.log-->
<param name="DatePattern" value=""logs_"yyyyMMdd".log"" />
<!--日志文件名是否是固定不变的-->
<param name="StaticLogFileName" value="false" />
<!--布局-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger scope=[%property{scope}] - %message %exception%newline" />
</layout>
</appender>
<!--控制台输出-->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger scope=[%property{scope}] - %message %exception%newline" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="DebugAppender" />
<appender-ref ref="RollingFile" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
五、在控制器中写入测试代码(WeatherForecastController.cs)
public class WeatherForecastController : ControllerBase
{
//...
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogTrace("trace");
_logger.LogDebug("debug");
_logger.LogInformation("info");
_logger.LogWarning("warn");
_logger.LogError("error");
_logger.LogCritical("critical");
using (_logger.BeginScope("测试日志的Scope"))
{
_logger.LogTrace("scope-trace");
_logger.LogDebug("scope-debug");
_logger.LogInformation("scope-info");
_logger.LogWarning("scope-warn");
_logger.LogError("scope-error");
_logger.LogCritical("scope-critical");
}
_logger.LogTrace("Scope已经结束了。。。");
var rng = new Random();
throw new Exception("测试异常日志");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
//...
}
六、运行查看效果
控制台效果:
文件效果:
上一篇: css中的position定位
下一篇: 服务端鉴权之Session/Cookie