1.创建一个新的ASP.NET Core项目
2.添加项目依赖
3.在项目目录下添加nlog.config文件:
1 <?xml version="1.0" encoding="utf-8" ?> 2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 autoReload="true" 5 internalLogLevel="Warn" 6 internalLogFile="c:\temp\internal-nlog.txt"> 7 8 <!-- 加载ASP.NET Core插件 --> 9 <extensions> 10 <add assembly="NLog.Web.AspNetCore"/> 11 </extensions> 12 13 <!-- 输出目的地 --> 14 <targets> 15 <!-- 输出到文件,这个文件记录所有日志 --> 16 <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log" 17 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" /> 18 19 <!-- 另外一个日志记录文件,户口也跳过Microsoft开头相关日志信息 --> 20 <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log" 21 layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> 22 23 <!-- write to the void aka just remove --> 24 <target xsi:type="Null" name="blackhole" /> 25 </targets> 26 27 <!-- 写入目的地的规则 --> 28 <rules> 29 <!--全部记录,包括Microsoft开头的相关日志信息--> 30 <logger name="*" minlevel="Trace" writeTo="allfile" /> 31 32 <!--跳过Microsoft开头的相关日志信息--> 33 <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> 34 <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> 35 </rules> 36 </nlog>
3.将nlog.config复制到bin文件夹
4.在startup.cs文件中添加(红字):
1 using NLog.Extensions.Logging; 2 using NLog.Web; 3 4 public Startup(IHostingEnvironment env) 5 { 6 env.ConfigureNLog("nlog.config"); 7 } 8 9 public void ConfigureServices(IServiceCollection Services) 10 { 11 //call this in case you need aspnet-user-authtype/aspnet-user-identity 12 services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 13 } 14 15 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 16 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 17 { 18 19 //add NLog to ASP.NET Core 20 loggerFactory.AddNLog(); 21 22 //add NLog.Web 23 app.AddNLogWeb(); 24 25 //note: remove the old loggerFactory, like loggerFactory.AddConsole and loggerFactory.AddDebug
5.记录日志
1 public class HomeController : Controller 2 { 3 private readonly ILogger<HomeController> _logger; 4 5 public HomeController(ILogger<HomeController> logger) 6 { 7 _logger = logger; 8 } 9 10 public IActionResult Index() 11 { 12 _logger.LogInformation("Index page says hello"); 13 return View(); 14 }
6.运行ASP.NET Core网站,会生成两个文件