网站首页> 文章专栏> .Net Core3.1配置Nlog日志
.Net Core3.1配置Nlog日志
日期:2020-09-02 23:25:02 作者:jzlnice 浏览量:2875

参考链接:https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-3

参考链接:https://www.cnblogs.com/fancyblogs/p/12924263.html


1、引用程序集,添加Nlog

安装或更新到最新Nlog包:

    NLog.Web.AspNetCore 4.9+

2、创建一个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="Info"
      internalLogFile="c:\temp\internal-nlog.txt">
  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>
  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>
  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />
    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

3、设置nlog.config属性为“如果较新则复制”


4、修改Program.cs 注入, UseNLog()

using System;using NLog.Web;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Logging;using Microsoft.Extensions.Hosting;
public static void Main(string[] args)
{
    var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    try
    {
        logger.Debug("init main");
        CreateHostBuilder(args).Build().Run();
    }
    catch (Exception exception)
    {
        //NLog: catch setup errors
        logger.Error(exception, "Stopped program because of exception");
        throw;
    }
    finally
    {
        // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
        NLog.LogManager.Shutdown();
    }
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
          webBuilder.UseStartup<Startup>();
      })
      .ConfigureLogging(logging =>
      {
          logging.ClearProviders();
          logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
      })
      .UseNLog();  // NLog: Setup NLog for Dependency injection

5、配置 appsetting.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

6、使用日志

 
using Microsoft.Extensions.Logging;
public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into HomeController");
    }
    public IActionResult Index()
    {
        _logger.LogInformation("Hello, this is the index!");
        return View();
    }

7、输出日志文件


8、封装

可以将Nlog的使用封装在一个类中,方便调用

using System;
using System.Collections.Generic;
using System.Text;
using NLog;
namespace App.Common.Log
{
    /// <summary>
    /// 日志
    /// </summary>
   public class NLogger
    {
        private static Logger logger;
        static NLogger()
        {
            logger = LogManager.GetCurrentClassLogger();
            logger = logger.Factory.GetLogger("*");  }
        /// <summary>
        /// 记录调试信息
        /// </summary>
        /// <param name="info">日志信息</param>

        public static void Debug(string info)
        {
            logger.Debug(info);
        }

        /// <summary>
        /// 记录信息
        /// </summary>
        /// <param name="info">日志信息</param>
        public static void Info(string info)
        {
            logger.Info(info);
        }

        /// <summary>
        /// 记录警告信息
        /// </summary>
        /// <param name="info">日志信息</param>
        public static void Warn(string info)
        {
            logger.Info(info);
        }

        /// <summary>
        /// 记录异常信息
        /// </summary>
        /// <param name="exception">异常</param>
        public static void Error(Exception exception)
        {
            logger.Error(GetExceptionFullMessage(exception));
        }


        /// <summary>
        /// 记录致命错误
        /// </summary>
        /// <param name="info">错误信息</param>
        public static void Fatal(string info)
        {
            logger.Fatal(info);
        }

        /// <summary>
        /// 获取完整的异常消息,包括内部异常消息
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        internal static string GetExceptionFullMessage (Exception exception)
        {
            if(exception==null)
            {
                return null;
            }
            var message = new StringBuilder(exception.Message);
            var innerException = exception.InnerException;
            while(innerException!=null)
            {
                message.Append("--->");
                message.Append(innerException.Message);
                innerException = innerException.InnerException;
            }
            return message.ToString();
        }
    }


9、使用方法

NLogger.Info("这是一个日志信息");


来说两句吧
最新评论
    热门文章
      随便看看