1. Install NuGet package
1、Install-Package NLog.Web.AspNetCore
2、Install-Package NLog
Edit in csproj:
<PackageReference Include="NLog" Version="4.5.3" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.5.3" />
2. Create an 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" autoReload="true" throwConfigExceptions="true" internalLogLevel="info" internalLogFile="D:\temp\internal-nlog.txt"> <!-- 要写的目标--> <targets> <!--将日志写入文件 --> <target xsi:type="File" name="allfile" fileName="D:\temp\nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" /> <!-- 启用asp.net核心布局渲染器 --> <target xsi:type="File" name="ownFile-web" fileName="D:\temp\nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> </targets> <!-- Rule mapping from logger name to target --> < rules > <!-- All records, including from Microsoft --> < logger name ="*" minlevel ="Trace" writeTo ="allfile" /> <!-- Skip non-critical Microsoft logs, so only log your own --> < logger name ="Microsoft.*" maxlevel ="Info" final ="true" /> <!-- BlackHole --> < logger name ="*" minlevel ="Trace" writeTo ="ownFile-web" /> </ rules > </ nlog >
Layout Renderer Usage Guidelines
- ${aspnet-MVC-Action} - ASP.NET MVC action name
- ${aspnet-MVC-Controller} - ASP.NET MVC controller name
- ${aspnet-Application} - ASP.NET application variables.
- ${aspnet-Item} - ASP.NET
HttpContext
item variable. - ${aspnet-Request} - ASP.NET request variables.
- ${aspnet-Request-Cookie} - ASP.NET request cookie content.
- ${aspnet-Request-Host} - ASP.NET request host.
- ${aspnet-Request-Method} - ASP.NET request method (GET, POST, etc).
- ${aspnet-Request-QueryString} - ASP.NET request query string.
- ${aspnet-Request-Referrer} - ASP.NET request referrer.
- $ {aspnet-Request-UserAgent} - ASP.NET请求useragent。
- ${aspnet-Request-Url} - ASP.NET request URL.
- $ {aspnet-Session} - ASP.NET Session变量。
- ${aspnet-SessionId} - ASP.NET session ID variable.
- ${aspnet-TraceIdentifier} - ASP.NET trace identifier
- ${aspnet-UserAuthType} - ASP.NET user authentication.
- ${aspnet-UserIdentity} - ASP.NET user variable.
- ${iis-site-name} - IIS site name.
3、在csproj
Manually edit the file and add
<ItemGroup> <Content Update="nlog.config" CopyToOutputDirectory="Always" /> </ItemGroup>
4. Update program.cs
public static void Main(string[] args) { // NLog: first set up logger to catch all errors var logger = NLog.Web.NLogBuilder.ConfigureNLog( " nlog.config " ).GetCurrentClassLogger(); try { logger.Debug("init main"); BuildWebHost(args).Run(); } catch (Exception exception) { // NLog:catch安装错误 logger.Error(exception, "Stopped program because of exception"); throw; } finally { // Make sure to flush and stop internal timers/threads before exiting the application (avoids segmentation faults on Linux) NLog.LogManager.Shutdown(); } } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }) .UseNLog() // NLog: setup NLog is used for dependency injection.Build ();
5. Configure appsettings.json
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning", "Microsoft": "Information" } } }
6. Write a log
private readonly ILogger _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(); }
7. Output example