一、.net core配置使用Nlog日志
1. nlog介绍:NLog((http://www.nlog-project.org)是一个基于.NET平台编写的类库,我们可以使用NLog在应用程序中添加极为完善的跟踪调试代码。NLog完全实现了我们上面的期望目标,并且还远远不止这些……
NLog允许我们自定义从跟踪消息的来源(source)到记录跟踪信息的目标(target)的规则(rules)。记录跟踪信息的目标(target)可以为如下几种形式:
- 文件
- 文本控制台
- 数据库
- 网络中的其它计算机(通过TCP或UDP)
- 基于MSMQ的消息队列
2. core中使用nlog日志记录:添加引用nlog.config和Nlog.Web.AspNetCore。
3. 修改配置program
1 public class Program 2 { 3 public static void Main(string[] args) 4 { 5 CreateHostBuilder(args).Build().Run(); 6 7 var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); 8 try 9 { 10 logger.Debug("init main"); 11 CreateHostBuilder(args).Build().Run(); 12 } 13 catch (Exception exception) 14 { 15 //NLog: catch setup errors 16 logger.Error(exception, "Stopped program because of exception"); 17 throw; 18 } 19 finally 20 { 21 // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) 22 NLog.LogManager.Shutdown(); 23 } 24 } 25 26 public static IHostBuilder CreateHostBuilder(string[] args) => 27 Host.CreateDefaultBuilder(args) 28 .ConfigureWebHostDefaults(webBuilder => 29 { 30 webBuilder.UseStartup<Startup>(); 31 }).ConfigureLogging(logging => 32 { 33 logging.ClearProviders(); // 这个方法会清空所有控制台的输出 34 logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); 35 }) 36 .UseNLog(); // 使用NLog; 37 }
4. 修改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 xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"> 5 <targets> 6 <target xsi:type="File" name="LogFile" fileName="${basedir}/logs/${shortdate}.log" 7 layout="${longdate} ${uppercase:${level}} ${message}" /> 8 </targets> 9 10 <rules> 11 <logger name="*" minlevel="Debug" writeTo="LogFile" /> 12 </rules> 13 </nlog>
5. 使用日志:
注入: private readonly ILogger<WeatherForecastController> _logger; 使用: _logger.LogError("报错了");
谢谢学习,转发请标明出处!https://www.cnblogs.com/wangjinya/p/12935564.html