Asp.net Core中使用NLog,並封裝成公共的日誌方法

一、安裝NLoggit

"NLog.Extensions.Logging": "1.0.0-rtm-alpha4"github

二、配置NLogapp

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            //配置NLog
 loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config");

            app.UseApplicationInsightsRequestTelemetry();

三、nlog.configui

<?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"
      throwConfigExceptions="true"
      internalLogLevel="Debug"
      internalLogToTrace="true">

  <targets>
    <target name="logfile"
            xsi:type="File"
            fileName="logs/${shortdate}.log"
            layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}" />
    <target name="console"
            xsi:type="ColoredConsole"
            layout="${longdate} [${level:uppercase=true}] ${callsite:className=true:methodName=true:skipFrames=1} ${message} ${exception} @${callsite:fileName=true:includeSourcePath=true}"/>
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <rules>
    <!-- 除非調試須要,把 .NET Core 程序集的 Debug 輸出都屏蔽 Trace -》Debug-》 Information -》Warning-》 Error-》 Critical-->
    <logger name="Microsoft.*" minLevel="Trace" writeTo="blackhole" final="true" />
    <!-- 除非調試須要,把系統的 Debug 輸出都屏蔽 -->
    <logger name="System.*" minLevel="Trace" writeTo="blackhole" final="true" />
    
    <logger name="*" minlevel="Debug" writeTo="logfile,console" />
  </rules>
</nlog>

NLog的異常等級:Trace -》Debug-》 Information -》Warning-》 Error-》 Criticalspa

注意配置文件中能夠移除Microsoft和System開頭的組件輸出的日誌,否則日誌會很是多調試

NLog的更多配置請參考:https://github.com/NLog/NLog/wiki/Callsite-layout-renderer日誌

四、封裝成公共方法code

using NLog;
using System;
using System.Diagnostics;

namespace UFX.Tools
{
    public class LogHelper
    {
        private static readonly Logger log = LogManager.GetLogger("");
        public static void Error(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Error("#" + msg);
            else
                log.Error("#" + msg + "  " + exp.ToString());
        }

        public static void Debug(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Debug("#" + msg);
            else
                log.Debug("#" + msg + "  " + exp.ToString());
        }

        public static void Info(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Info("#" + msg);
            else
                log.Info("#" + msg + "  " + exp.ToString());
        }


        public static void Warn(object msg, Exception exp = null)
        {
            if (exp == null)
                log.Warn("#" + msg);
            else
                log.Warn("#" + msg + "  " + exp.ToString());
        }
    }
}

五、其餘方法中使用直接LogHelper.Debug("")等便可orm

但你會發現日誌輸出的方法中,全部異常都來自Tools.LogHelper,這樣就不能準確的返回異常的方法,代碼位置了,在.Net Core以前的版本中,咱們能夠經過StackFrames來找到調用方法,可是.Net Core這個方法無論用了。xml

好在NLog已經爲咱們考慮到這個問題了,配置文件中直接能夠定義須要打印的方法名稱,須要網上尋找的Frame個數

${callsite:className=true:methodName=true:skipFrames=1}

更多配置請參考:https://github.com/NLog/NLog/wiki/Callsite-layout-renderer

using NLog;using System;using System.Diagnostics;namespace UFX.Tools{    public class LogHelper    {        private static readonly Logger log = LogManager.GetLogger("");        public static void Error(object msg, Exception exp = null)        {            if (exp == null)                log.Error("#" + msg);            else                log.Error("#" + msg + "  " + exp.ToString());        }        public static void Debug(object msg, Exception exp = null)        {            if (exp == null)                log.Debug("#" + msg);            else                log.Debug("#" + msg + "  " + exp.ToString());        }        public static void Info(object msg, Exception exp = null)        {            if (exp == null)                log.Info("#" + msg);            else                log.Info("#" + msg + "  " + exp.ToString());        }        public static void Warn(object msg, Exception exp = null)        {            if (exp == null)                log.Warn("#" + msg);            else                log.Warn("#" + msg + "  " + exp.ToString());        }    }}

相關文章
相關標籤/搜索