安装NuGet包
PM> Install-Package Serilog
PM> Install-Package Serilog.AspNetCore
PM> Install-Package Serilog.Sinks.Console
PM> Install-Package Serilog.Sinks.File
在Program.cs文件中配置
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>().UseSerilog((context, configuration) => { configuration .MinimumLevel.Warning() // 日志调用类命名空间如果以 Microsoft 开头,覆盖日志输出最小级别为 Information .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() // 配置日志输出到控制台 .WriteTo.Console() // 配置日志输出到文件,文件输出到当前项目的 logs 目录下 // 日记的生成周期为每天 .WriteTo.File(Path.Combine("logs", @"log.txt"), rollingInterval: RollingInterval.Day); });
使用:
private readonly ILogger _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { Test ss = new Test(); ss.Add("1", "a"); return View(); }
经自身测试貌似自动记录了全局异常,不用另外配置全局异常捕捉。
文章内容参考:https://blog.csdn.net/Upgrader/article/details/88323907