在ASP.Net Core Web API中使用Log4Net

2021-03-01 09:25

阅读:486

标签:滚动   evel   value   bho   mini   web api   locking   写入   net   

1、引用Log4Net

在Nuget中引入Log4Net和Microsoft.Extensions.Logging.Log4Net.AspNetCore。

2、配置Log4Net

(1) 整理配置文件

(2) 在Program类中配置Log4Net

public static IHostBuilder CreateHostBuilder(string[] args) =>
	Host.CreateDefaultBuilder(args)
		.ConfigureLogging(loggingBuilder =>
		{
			//支持IOC控制反转
			loggingBuilder.AddLog4Net("Config/log4net.config");
		})
		.ConfigureWebHostDefaults(webBuilder =>
		{
			webBuilder.UseStartup();
		});

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 _logger;

	public WeatherForecastController(ILogger logger)
	{
		_logger = logger;
	}

	[HttpGet]
	public IEnumerable 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);

 

在ASP.Net Core Web API中使用Log4Net

标签:滚动   evel   value   bho   mini   web api   locking   写入   net   

原文地址:https://www.cnblogs.com/xhubobo/p/14397662.html


评论


亲,登录后才可以留言!