背景
.NET Core 支持适用于各种内置和第三方日志记录提供程序的日志记录 API。 先来看下如何将日志记录 API 与内置提供程序一起使用。
调用 CreateDefaultBuilder,这将添加以下日志记录提供程序:
控制台
调试
EventSource
EventLog:仅限 Windows
public class Program {public static void Main(string[] args){CreateHostBuilder(args).Build().Run();}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();}); }
实现思路
若要替代Host.CreateDefaultBuilder 添加的默认日志记录提供程序集,请调用 ClearProviders 并添加所需的日志记录提供程序。 例如,以下代码:
调用 ClearProviders 以从生成器中删除所有 ILoggerProvider 实例。
添加控制台日志记录提供程序。
public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureLogging(logging =>{logging.ClearProviders();logging.AddConsole();}).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();});
Nlog案例
使用第三方替代,以Nlog为例
修改 program.cs
using System;
using NLog.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;public static void Main(string[] args)
{var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();try{logger.Debug("init main");CreateHostBuilder(args).Build().Run();}catch (Exception exception){//NLog: catch setup errorslogger.Error(exception, "Stopped program because of exception");throw;}finally{// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)NLog.LogManager.Shutdown();}
}public static IHostBuilder CreateHostBuilder(string[] args) =>Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder =>{webBuilder.UseStartup<Startup>();}).ConfigureLogging(logging =>{logging.ClearProviders();logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);}).UseNLog(); // NLog: Setup NLog for Dependency injection
写日志
using Microsoft.Extensions.Logging;public class HomeController : Controller
{private readonly ILogger<HomeController> _logger;public HomeController(ILogger<HomeController> logger){_logger = logger;_logger.LogDebug(1, "NLog injected into HomeController");}public IActionResult Index(){_logger.LogInformation("Hello, this is the index!");return View();}