以ASP.NET MVC Core為例。

在Program.cs中,

 public static IHostBuilder CreateHostBuilder(string[] args) =>
   Host.CreateDefaultBuilder(args)

CreateDefaultBuilder的原始碼已經做了(即內建了):

 .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
    }).

所以不需要手工定義providers。如果想使用別的providers,需要如此:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureLogging(logBuilder =>
                {
                   logBuilder.ClearProviders(); // removes all providers from LoggerFactory
                   logBuilder.AddConsole();
                   logBuilder.AddTraceSource("Information, ActivityTracing"); // Add Trace listener provider
                }) 
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

如果記日誌到文件中,需要安裝nuget包 Serilog.Extensions.Logging.File

然後在Startup.cs中,增加:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{
    // other code remove for clarity 
    loggerFactory.AddFile("Logs/mylog-{Date}.txt");
}

以HomeController為例,如下記日誌:

namespace AspDotNetCoreMvcApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger<HomeController> logger){
            _logger = logger;
        }
        
        public IActionResult Index()
        {
            _logger.LogInformation("Log message in the Index() method");

            return View();
        }

        public IActionResult About()
        {
            _logger.LogInformation("Log message in the About() method");
            
            return View();
        }
    }
}

Microsoft.Extensions.Logging命名空間定義了日誌級別和擴展方法:

日誌級別和擴展方法
枚舉名字 枚舉值 ILogger擴展方法
Trace 0 LogTrace
Debug 1 LogDebug
Information 2 LogInformation
Warning 3 LogWarning
Error 4 LogError
Critical 5 LogCritical
None 6

在appsettings.json中,可定義日誌的級別:

// appsettings.json
{
  "Logging": {
    "LogLevel": { // All providers
      "Default": "Information",
      "Microsoft": "Warning"
    }
    "Console": {
      "LogLevel": { // Console provider
        "Default": "Information", // Overrides preceding LogLevel:Default setting.
        "Microsoft": "Trace" // Writes at Trace Level inside the Microsoft assembly
      }        
    }
  }
}