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