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());        }    }}

相关文章
相关标签/搜索