Log4Net在Net6 WebApi中的应用
Log4Net在Net6 WebApi中的应用
-
下载依赖
- log4net
- Microsoft.Extensions.Logging.Log4Net.AspNetCore
-
拷贝日志配置文件 \Config\log4net.config,必须设置为始终复制
<?xml version="1.0" encoding="utf-8"?> <configuration> <!-- This section contains the log4net configuration settings --> <log4net> <!--根配置--> <root> <!--日志级别:可选值: ERROR > WARN > INFO > DEBUG --> <level value="DEBUG"/> <appender-ref ref="ErrorLog" /> </root> <!-- 错误 Error.log--> <appender name="ErrorLog" type="log4net.Appender.RollingFileAppender"> <!--目录路径,可以是相对路径或绝对路径--> <file value="Logs/" /> <!--文件名,按日期生成文件夹--> <param name="DatePattern" value="yyyy-MM-dd'.log'"/> <!--追加到文件--> <appendToFile value="true"/> <!--创建日志文件的方式,可选值:Date[日期],文件大小[Size],混合[Composite]--> <rollingStyle value="Composite"/> <!--写到一个文件--> <staticLogFileName value="false"/> <!--单个文件大小。单位:KB|MB|GB--> <maximumFileSize value="50MB"/> <!--最多保留的文件数,设为"-1"则不限--> <maxSizeRollBackups value="-1"/> <!--日志格式--> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %message%newline------------------------------------------------------------------------------------%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="ALL" /> <param name="LevelMax" value="FATAL" /> </filter> </appender> </log4net> </configuration>
-
创建过滤类Log4Extention
public static class Log4Extention { public static void InitLog4(ILoggingBuilder loggingBuilder) { loggingBuilder.AddFilter("System", LogLevel.Warning); loggingBuilder.AddFilter("Microsoft", LogLevel.Warning);//过滤掉系统默认的一些日志 loggingBuilder.AddLog4Net(new Log4NetProviderOptions() { Log4NetConfigFileName = "Config/log4net.config", Watch = true }); } } }
-
Programm.cs
#region 添加Log4net // 必须引入该包 Log4Net 以及 Microsoft.Extensions.Logging.Log4Net.AspNetCore builder.Host.ConfigureLogging((context, loggingBuilder) => { Log4Extention.InitLog4(loggingBuilder); }); #endregion
-
调用
[ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; _logger.LogInformation("WeatherForecastController 构造了"); } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { _logger.LogWarning("程序Get被调用了"); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
世界上没有什么事情是跑步解决不了的,如果有,那就再跑一会!