在ASP.Net Core Web API中使用Log4Net
1、引用Log4Net
在Nuget中引入Log4Net和Microsoft.Extensions.Logging.Log4Net.AspNetCore。
2、配置Log4Net
(1) 整理配置文件
<?xml version="1.0" encoding="utf-8" ?> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\log.txt" /> <!-- 追加日志内容 --> <appendToFile value="true" /> <!-- 修小锁定模型:允许多个进程写入同一个文件 --> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <!-- 备份文件格式 --> <datePattern value="yyyyMMdd.txt" /> <!-- 仅根据文件大小滚动文件 --> <rollingStyle value="Size" /> <!-- 备份文件的个数(-1不做限制) --> <maxSizeRollBackups value="-1" /> <!-- 单个日志文件最大的大小 --> <maximumFileSize value="50MB" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="RollingLogFileAppender" /> </root> </log4net>
(2) 在Program类中配置Log4Net
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(loggingBuilder => { //支持IOC控制反转 loggingBuilder.AddLog4Net("Config/log4net.config"); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
3、使用Log4Net
通过依赖注入使用Logger。
[ApiController] [Route("api/[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; } [HttpGet] public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("Get WeatherForecast"); var rng = new Random(); 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(); } }
4、过滤系统日志
//过滤日志 loggingBuilder.AddFilter("System", LogLevel.Information); loggingBuilder.AddFilter("System", LogLevel.Warning); loggingBuilder.AddFilter("Microsoft", LogLevel.Information); loggingBuilder.AddFilter("Microsoft", LogLevel.Warning); loggingBuilder.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Information); loggingBuilder.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning);