.Net Core WebApi(3)—NLog

在.Net Core中,微软提供的内置的日志组件没有实现将日志记录到文件、数据库上。
这里使用NLog替代内置的日志组件

1.在项目中引入NuGet包
    NLog  
      NLog.Web.AspNetCor
 
⒉在项目的根目录中创建NLog配置文件
右击项目“ 添加”->"Web配置文件"->新建“ nlog.config
 1 "1.0" encoding="utf-8" ?>
 2 "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   
 9     
10     "File" name="allfile" fileName="logs/all/nlog-all-${shortdate}.log"
11              layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
12     "File" name="ownFile-web" fileName="logs/my/nlog-cwiosapi-${shortdate}.log"
13              layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
14     "Null" name="blackhole" />
15   
16   
17     
18     "*" minlevel="Trace" writeTo="allfile" />
19     
20     "Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
21     "*" minlevel="Trace" writeTo="ownFile-web" />
22   
23 
 
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 _logger;
 6         /// 
 7         /// 构造器
 8         /// 
 9         /// 
10         /// 
11         public StudentController(IStudentServices services, ILogger   logger)
12         {
13             _service = services;
14             _logger = logger;
15         }
16         #region base
17         /// 
18         /// 添加
19         /// 
20         /// 
21         /// 
22         [HttpPost("AddByService")]
23         public PageResponse 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.生成的日志

你可能感兴趣的:(.Net Core WebApi(3)—NLog)