.Net Core 3.1之使用扩展log4net

Step1:引入包Microsoft.Extensions.Logging.Log4.AspNetCore

Step2:写log4net.config文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <log4net>
 3 <!-- Define some output appenders -->
 4 <appender name="rollingAppender" type="log4net.Appender.RollingFileAppender">
 5 <file value="log\log.txt" />
 6 <!--追加日志内容-->
 7 <appendToFile value="true" />
 8 
 9 <!--防止多线程时不能写Log,官方说线程非安全-->
10 <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
11 
12 <!--可以为:Once|Size|Date|Composite-->
13 <!--Composite为Size和Date的组合-->
14 <rollingStyle value="Composite" />
15 
16 <!--当备份文件时,为文件名加的后缀-->
17 <datePattern value="yyyyMMdd.TXT" />
18 
19 <!--日志最大个数,都是最新的-->
20 <!--rollingStyle节点为Size时,只能有value个日志-->
21 <!--rollingStyle节点为Composite时,每天有value个日志-->
22 <maxSizeRollBackups value="20" />
23 
24 <!--可用的单位:KB|MB|GB-->
25 <maximumFileSize value="3MB" />
26 
27 <!--置为true,当前最新日志文件名永远为file节中的名字-->
28 <staticLogFileName value="true" />
29 
30 <!--输出级别在INFO和ERROR之间的日志-->
31 <filter type="log4net.Filter.LevelRangeFilter">
32 <param name="LevelMin" value="ALL" />
33 <param name="LevelMax" value="FATAL" />
34 </filter>
35 <layout type="log4net.Layout.PatternLayout">
36 <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
37 </layout>
38 </appender>
39 <root>
40 <priority value="ALL"/>
41 <level value="ALL"/>
42 <appender-ref ref="rollingAppender" />
43 </root>
44 </log4net>
View Code

 

Step3:在Program.cs里添加配置

1 public static IHostBuilder CreateHostBuilder(string[] args) =>
2   Host.CreateDefaultBuilder(args)
3   .ConfigureLogging((context,logginBuilder)=> {
4     logginBuilder.AddLog4Net();
5   })
6   .ConfigureWebHostDefaults(webBuilder =>
7   {
8     webBuilder.UseStartup<Startup>();
9 });

 

Step:4在controller里进行使用

  

 1 public class WeatherForecastController : ControllerBase
 2 {
 3   private static readonly string[] Summaries = new[]
 4   {
 5     "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
 6   };
 7 
 8   private readonly ILogger<WeatherForecastController> _logger;
 9 
10   public WeatherForecastController(ILogger<WeatherForecastController> logger)
11   {
12     _logger = logger;
13   }
14 
15   [HttpGet]
16   public IEnumerable<WeatherForecast> Get()
17   {
18     this._logger.LogInformation("information test");
19     var rng = new Random();
20     return Enumerable.Range(1, 5).Select(index => new WeatherForecast
21     {
22       Date = DateTime.Now.AddDays(index),
23       TemperatureC = rng.Next(-20, 55),
24       Summary = Summaries[rng.Next(Summaries.Length)]
25     })
26     .ToArray();
27   }
28 }

 

posted @ 2020-03-19 23:15  猪猪星竹  阅读(532)  评论(0编辑  收藏  举报