# Logging
Getting started with ASP.NET Core 6 · NLog/NLog Wiki · GitHub
1. ASP.NET Core built-in logging providers
Console
Debug
EventSource
EventLog
TraceSource
AzureAppServicesFile
AzureAppServicesBlob
ApplicationInsights
2. Using NLog in ASP.NET Core
- Install NLog.Web.AspNetCore nuget package
- Create nlog.config file
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target name="allfile" xsi:type="File"
fileName="c:\DemoLogs\nlog-all-${shortdate}.log"/>
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
</rules>
</nlog>
- Enable copy to bin folder for nlog.config
- Enable NLog as one of the Logging Provider
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
// Enable NLog as one of the Logging Provider
logging.AddNLog();
})
.UseStartup<Startup>();
- If you want only NLog as the logging provider, clear all the logging providers and then add NLog.
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
// Remove all the default logging providers
logging.ClearProviders();
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
// Add NLog as the Logging Provider
logging.AddNLog();
})
.UseStartup<Startup>();
- define different logLevel for each controller
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"EmployeeManagement.Controllers.HomeController": "Trace",
"EmployeeManagement.Models.SQLEmployeeRepository": "Error",
"Microsoft": "Warning"
}
}
}
No comments:
Post a Comment