本篇是在上一篇的基礎上添加日誌功能,並記錄NLog在Asp.Net Core裏的使用方法。html
1 { 2 "version": "1.0.0-*", 3 "buildOptions": { 4 "debugType": "portable", 5 "emitEntryPoint": true 6 }, 7 "dependencies": { 8 "Microsoft.NETCore.App": { 9 "type": "platform", 10 "version": "1.0.0" 11 }, 12 "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", 13 "Microsoft.AspNetCore.Mvc": "1.0.0", 14 "Microsoft.Extensions.Logging": "1.0.0", 15 "Microsoft.Extensions.Logging.Console": "1.0.0", 16 "Microsoft.Extensions.Logging.Debug": "1.0.0", 17 "Microsoft.Extensions.Logging.Filter": "1.0.0" 18 }, 19 "frameworks": { 20 "netcoreapp1.0": { 21 "imports": "dnxcore50" 22 } 23 } 24 }
1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.Extensions.DependencyInjection; 3 using Microsoft.Extensions.Logging; 4 5 namespace WebApiFrame 6 { 7 public class Startup 8 { 9 public void ConfigureServices(IServiceCollection services) 10 { 11 // 注入MVC框架 12 services.AddMvc(); 13 } 14 15 public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 16 { 17 // 添加日誌支持 18 loggerFactory.AddConsole(); 19 loggerFactory.AddDebug(); 20 21 // 添加MVC中間件 22 app.UseMvc(); 23 } 24 } 25 }
日誌級別從低到高一共六級,默認狀況下,控制檯上輸出的日誌會採起下面的格式:web
咱們在DemoController.cs控制器裏演示如何設置和輸出對應級別的日誌。json
1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.Extensions.DependencyInjection; 3 using Microsoft.Extensions.Logging; 4 5 namespace WebApiFrame 6 { 7 public class Startup 8 { 9 public void ConfigureServices(IServiceCollection services) 10 { 11 // 注入MVC框架 12 services.AddMvc(); 13 } 14 15 public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 16 { 17 // 添加日誌支持 18 19 // 設置日誌最小級別Warning 20 loggerFactory.AddConsole(LogLevel.Warning); 21 22 //loggerFactory.AddDebug(); 23 24 // 添加MVC中間件 25 app.UseMvc(); 26 } 27 } 28 }
1 using System; 2 using Microsoft.AspNetCore.Mvc; 3 using Microsoft.Extensions.Logging; 4 using WebApiFrame.Models; 5 6 namespace WebApiFrame.Controllers 7 { 8 9 [Route("api/[controller]")] 10 public class UsersController : Controller 11 { 12 private ILogger<UsersController> _logger; 13 14 public UsersController(ILogger<UsersController> logger){ 15 _logger = logger; 16 } 17 18 [HttpGet("{id}")] 19 public IActionResult Get(int id) 20 { 21 // 演示日誌輸出 22 _logger.LogInformation("This is Information Log!"); 23 _logger.LogWarning("This is Warning Log!"); 24 _logger.LogError("This is Error Log!"); 25 26 var user = new User() { Id = id, Name = "Name:" + id, Sex = "Male" }; 27 return new ObjectResult(user); 28 } 29 30 [HttpPost] 31 public IActionResult Post([FromBody] User user){ 32 if(user == null){ 33 return BadRequest(); 34 } 35 36 // TODO:新增操做 37 user.Id = new Random().Next(1, 10); 38 return CreatedAtAction("Get", new { id = user.Id }, user); 39 } 40 41 [HttpPut("{id}")] 42 public IActionResult Put(int id, [FromBody] User user){ 43 if(user == null){ 44 return BadRequest(); 45 } 46 47 // TODO: 更新操做 48 return new NoContentResult(); 49 } 50 51 [HttpDelete("{id}")] 52 public void Delete(int id){ 53 // TODO: 刪除操做 54 55 } 56 } 57 }
1 public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 2 { 3 // 添加日誌支持 4 5 // 設置日誌最小輸出級別爲Error 6 loggerFactory.WithFilter(new FilterLoggerSettings() 7 { 8 // 設置以命名空間開頭的日誌的最小輸出級別 9 { "Microsoft", LogLevel.Warning }, 10 { "WebApiFrame", LogLevel.Error } 11 }).AddConsole(); 12 13 //loggerFactory.AddDebug(); 14 15 // 添加MVC中間件 16 app.UseMvc(); 17 }
NLog是一個簡單靈活的.Net日誌記錄類庫。相比Log4Net來講,配置要簡單許多。api
1 { 2 "version": "1.0.0-*", 3 "buildOptions": { 4 "debugType": "portable", 5 "emitEntryPoint": true 6 }, 7 "dependencies": { 8 "Microsoft.NETCore.App": { 9 "type": "platform", 10 "version": "1.0.0" 11 }, 12 "Microsoft.AspNetCore.Server.Kestrel": "1.0.0", 13 "Microsoft.AspNetCore.Mvc": "1.0.0", 14 "Microsoft.Extensions.Logging": "1.0.0", 15 "Microsoft.Extensions.Logging.Console": "1.0.0", 16 "Microsoft.Extensions.Logging.Debug": "1.0.0", 17 "Microsoft.Extensions.Logging.Filter": "1.0.0", 18 "NLog.Extensions.Logging": "1.0.0-rtm-alpha2" 19 }, 20 "frameworks": { 21 "netcoreapp1.0": { 22 "imports": "dnxcore50" 23 } 24 } 25 }
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="internal-nlog.txt"> 7 8 <!-- define various log targets --> 9 <targets> 10 <!-- write logs to file --> 11 <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log" 12 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> 13 14 15 <target xsi:type="File" name="ownFile-web" fileName="nlog-own-${shortdate}.log" 16 layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" /> 17 18 <target xsi:type="Null" name="blackhole" /> 19 </targets> 20 21 <rules> 22 <!--All logs, including from Microsoft--> 23 <logger name="*" minlevel="Trace" writeTo="allfile" /> 24 25 <!--Skip Microsoft logs and so log only own logs--> 26 <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> 27 <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> 28 </rules> 29 </nlog>
1 using Microsoft.AspNetCore.Builder; 2 using Microsoft.Extensions.DependencyInjection; 3 using Microsoft.Extensions.Logging; 4 using NLog.Extensions.Logging; 5 6 namespace WebApiFrame 7 { 8 public class Startup 9 { 10 public void ConfigureServices(IServiceCollection services) 11 { 12 // 注入MVC框架 13 services.AddMvc(); 14 } 15 16 public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 17 { 18 // 添加日誌支持 19 //loggerFactory.AddConsole(); 20 //loggerFactory.AddDebug(); 21 22 // 添加NLog日誌支持 23 loggerFactory.AddNLog(); 24 25 // 添加MVC中間件 26 app.UseMvc(); 27 } 28 } 29 }
生成的日誌文件和內容瀏覽器
最後,同時放開三種日誌輸出方式,不修改控制器裏的任何代碼,能夠發現將同時以三種方式記錄相同的日誌內容。app
1 public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 2 { 3 // 添加日誌支持 4 loggerFactory.AddConsole(); 5 loggerFactory.AddDebug(); 6 7 // 添加NLog日誌支持 8 loggerFactory.AddNLog(); 9 10 // 添加MVC中間件 11 app.UseMvc(); 12 }
在.Net Core框架裏,日誌功能主要由 ILoggerFactory, ILoggerProvider, ILogger 這三個接口體現:框架
ILoggerFactory:工廠接口。只提供註冊LoggerProvider的方法和建立單實例Logger對象的方法。dom
ILoggerProvider:提供真正具備日誌輸出功能的Logger對象的接口。每一種日誌輸出方式對應一個不一樣的LoggerProvider類。ide
ILogger:Logger接口。Logger實例內部會維護一個ILogger接口的集合,集合的每一項都是由對應的LoggerProvider類註冊生成的Logger對象而來。當調用Logger的日誌輸出方法時,實際是循環調用內部集合的每個Logger對象的輸出方法,因此就能看到上面出現的效果。ui