.Net Core WebApi(3)—NLog
在.Net Core中,微软提供的内置的日志组件没有实现将日志记录到文件、数据库上。
这里使用NLog替代内置的日志组件
1.在项目中引入NuGet包
NLog
NLog.Web.AspNetCore
⒉在项目的根目录中创建NLog配置文件
右击项目“添加”->"Web配置文件"->新建“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="internal-nlog.txt"> 7 <!-- 要写入的目标 --> 8 <targets> 9 <!--将日志写入到文件中--> 10 <target xsi:type="File" name="allfile" fileName="logs/all/nlog-all-${shortdate}.log" 11 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> 12 <target xsi:type="File" name="ownFile-web" fileName="logs/my/nlog-cwiosapi-${shortdate}.log" 13 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> 14 <target xsi:type="Null" name="blackhole" /> 15 </targets> 16 <rules> 17 <!--所有日志,包括来自Microsoft的日志--> 18 <logger name="*" minlevel="Trace" writeTo="allfile" /> 19 <!--跳过非关键的Microsoft日志,因此只记录自己的日志--> 20 <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" /> 21 <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> 22 </rules> 23 </nlog>
3.更改配置文件属性 Configure
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 2 { 3 loggerFactory.AddNLog();//添加NLog 4 //引入Nlog配置文件 5 env.ConfigureNLog("nlog.config"); 6 }
4.通过注入的方式使用
1 public class StudentController : Controller 2 { 3 4 private readonly IStudentServices _service; 5 private readonly ILogger<StudentController> _logger; 6 /// <summary> 7 /// 构造器 8 /// </summary> 9 /// <param name="services"></param> 10 /// <param name="logger"></param> 11 public StudentController(IStudentServices services, ILogger<StudentController> logger) 12 { 13 _service = services; 14 _logger = logger; 15 } 16 #region base 17 /// <summary> 18 /// 添加 19 /// </summary> 20 /// <param name="entity"></param> 21 /// <returns></returns> 22 [HttpPost("AddByService")] 23 public PageResponse<Student> AddByService(Student entity) 24 { 25 _logger.LogInformation("测试111"); 26 return _service.Add(entity); 27 } 28 #endregion 29 }
5.配置appsettings.json
1 { 2 "Logging": { 3 "LogLevel": { 4 "Default": "Warning" 5 } 6 }, 7 "AllowedHosts": "*" 8 }
6.生成的日志