• 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}");
                });
            }
  • 相关阅读:
    IIS部署web Service使用浏览器测试
    VS编译运行时提示:应用程序并行配置不正确,无法启动程序
    VS编译失败但是错误输出页中没有显示任何错误信息
    在客户端机器上使用PlSql,登录dba账号提示ORA-01031:insufficient privileges或 ORA-01017: invalid username/password; logon denied错误。
    FTP搭建注意事项
    .Net DLL类库引用时没有注释信息
    Oracle数据库连接超时
    Oracle触发器编译错误及解决方案
    VMware命令行模式安装CentOS 7后设置固定IP
    洲-国家 二级联动整体解决方案
  • 原文地址:https://www.cnblogs.com/zoro-zero/p/14296455.html
Copyright © 2020-2023  润新知