在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
添加项目依赖在项目目录下添加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> 将nlog.config复制到bin文件夹在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 记录日志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 } 运行ASP.NET Core网站,会生成两个文件nlog-own-2017-04-28.log和nlog-all-2017-04-28.log
|
请发表评论