1. 引入log4net、Microsoft.Extensions.Logging.Log4Net.AspNetCore包
2. 添加log4net配置文件
3. 在Program中添加如下代码:
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging((context, logger) => { logger.ClearProviders(); logger.AddLog4Net(new Log4NetProviderOptions() { Log4NetConfigFileName = "Config/log4net.xml", Watch = true }); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
4. 在需要记录日志的类中通过构造函数引入:
public class ActionExceptionHandlerAttribute : Attribute, IActionFilter { private readonly ILogger<ActionExceptionHandlerAttribute> _logger; public ActionExceptionHandlerAttribute(ILogger<ActionExceptionHandlerAttribute> logger) { _logger = logger; } }
原文地址:https://www.cnblogs.com/chikychan/p/12045176.html
时间: 2024-11-05 18:47:42