asp.net core 项目添加nlog日志(loggerFactor.AddNLog 过时处理(.net core 3.1))
1、安装Nlog包
使用nuget安装 NLog.Extensions.Logging 包,如下:
2、在项目添加nlog.config文件
3、nlog.config文件:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Warn"
internalLogFile="internal-nlog.txt">
<!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="Loggers/${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="ownFile-web" fileName="Loggers/${shortdate}.log"
layout="${longdate}|${logger}|${uppercase:${level}}| ${message} ${exception}" />
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
4、Program类中的Main添加如下代码:
public static void Main(string[] args) { CreateHostBuilder(args) .ConfigureLogging((ILoggingBuilder logBuilder) => { logBuilder.AddNLog(); logBuilder.AddConsole(); //logBuilder.confi NLog.LogManager.LoadConfiguration("Config/nlog.config"); }).Build().Run(); }
5、Controller 调用Nlog 方法
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace Core.RFID.WebApi.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { _logger.LogInformation("测试Log"); _logger.LogWarning("LogWarning测试Log"); _logger.LogError("LogError测试"); var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
6、运行效果:
7、说明,使用下面方法就会出现方法过时:应该使用第4步骤的方法,在 Program类中的Main添加如下代码:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactor) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } LogManager.LoadConfiguration("Config/nlog.config"); //添加NLog loggerFactor.AddNLog(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseStaticFiles(); app.UseEndpoints(endpoints => { //endpoints.MapControllers(); endpoints.MapControllerRoute("default", "api/{controller}/{action}"); }); }