NetCore2.2使用Nlog自定義日誌寫入路徑配置方式

在一些特定場景的業務需求下,日誌須要寫入到不一樣的路徑下提供日誌分析。
第一種:默認Nlog能夠經過日誌級別來區分路徑,
——優勢是不須要額外配置,開箱即用
——缺點是不夠靈活,若是超過級別數量,則不知足需求git

第二種:經過定義FileTarget來根據業務寫入不一樣的地址json

廢話很少說了,直接上代碼
一、建立NetCore,而且引入Nlog和NLog.Web.AspNetCore 這個就不介紹和貼圖了app

二、建立nlog配置文件dom

<?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">

  <targets>

    <target xsi:type="File" name="file" fileName="logs/nlog-all-${shortdate}.log"

            layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="exception" fileName="logs/nlog-exception-${shortdate}.log"

            layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="trace" fileName="logs/nlog-trace-${shortdate}.log"

            layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" encoding="utf-8" />

    <target xsi:type="Null" name="blackhole" />

  </targets>

  <rules>

    <logger name="*" minlevel="Trace" writeTo="file" />

    <!--日誌級別:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical-->

    <!--排除系統日誌-->

    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />

    <logger name="*" minlevel="Trace" writeTo="trace" />

    <logger name="*" minlevel="Error" maxlevel="Error" writeTo="exception" />

 

  </rules>

</nlog>

 

三、註冊,在Starup.cs文件中ide

Configure方法裏面註冊下
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            

            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");

            

            app.UseMvc();
        }

  

 
四、Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseNLog();

  

五、爲了擴展,咱們新建一個類來處理日誌的寫入,Process是被調用的寫入方法ui

using System;
using System.Text;
using NLog;

namespace CurLogger
{
    public class Logger
    {
        private static Logger instance = new Logger();
        private Logger() { }
        public static Logger GetInstance()
        {
            return instance;
        }

        /// <summary>
        /// 企業認證日誌地址
        /// </summary>
        public static string IdentityEnterprise;

        /// <summary>
        /// 政務認證日誌地址
        /// </summary>
        public static string IdentityGovernmentAffairs;
        /// <summary>
        /// 政務錯誤日誌地址
        /// </summary>
        public static string IdentityError;
        /// <summary>
        /// 隨機簽名日誌地址
        /// </summary>
        public static string RandomSign;

        /// <summary>
        /// 票據生成日誌地址
        /// </summary>
        public static string TicketCreate { get; set; }
        /// <summary>
        /// 票據驗證日誌地址
        /// </summary>
        public static string TicketInentity { get; set; }
        /// <summary>
        /// 票據異常日誌地址
        /// </summary>
        public static string TicketError { get; set; }

        public void Setting(LoggerConfig config)
        {
            IdentityEnterprise = config.IdentityEnterprise;
            IdentityGovernmentAffairs = config.IdentityGovernmentAffairs;
            IdentityError = config.IdentityError;
            RandomSign = config.RandomSign;
            TicketCreate = config.TicketCreate;
            TicketInentity = config.TicketInentity;
            TicketError = config.TicketError;
        }

        NLog.Logger _logger;
        private Logger(NLog.Logger logger)
        {
            _logger = logger;
        }
        public Logger(string name) : this(LogManager.GetLogger(name))
        {

        }

        public static Logger Default { get; private set; }
        static Logger()
        {
            Default = new Logger(LogManager.GetCurrentClassLogger());
        }

        public void Process(string msg, string path)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var fileTarget = NLog.LogManager.Configuration.FindTargetByName<NLog.Targets.FileTarget>("trace");
            fileTarget.FileName = "logs/" + path + "/${shortdate}_log.txt";
            fileTarget.Encoding = Encoding.GetEncoding("GB2312");
            _logger.Info(msg);
        }
    }

    public class LoggerConfig
    {
        //認證企業日誌地址
        public string IdentityEnterprise { get; set; }

        //認證政務日誌地址
        public string IdentityGovernmentAffairs { get; set; }
        //認證錯誤日誌地址
        public string IdentityError { get; set; }
        //隨機簽名日誌地址
        public string RandomSign { get; set; }
        //票據生成日誌地址
        public string TicketCreate { get; set; }
        //票據驗證日誌地址
        public string TicketInentity { get; set; }
        //票據異常日誌地址
        public string TicketError { get; set; }
    }
}

  

六、地址能夠經過配置文件配置,更加靈活,appsetting.jsonthis

"LogConfig": {
    "IdentityEnterprise": "identity/enterprise",
    "IdentityGovernmentAffairs": "identity/governmentaffairs",
    "IdentityError": "identity/error",
    "RandomSign": "randomsign",
    "TicketCreate": "ticket/create",
    "TicketInentity": "ticket/identity",
    "TicketError": "ticket/error"
  }

  

七、在Startup.cs中賦值給Logger裏面的地址spa

#region Init_Log_Path
            Logger.GetInstance().Setting(new LoggerConfig()
            {
                IdentityEnterprise = Configuration["LogConfig:IdentityEnterprise"],
                IdentityGovernmentAffairs = Configuration["LogConfig:IdentityGovernmentAffairs"],
                IdentityError = Configuration["LogConfig:IdentityError"],
                RandomSign = Configuration["LogConfig:RandomSign"],
                TicketCreate = Configuration["LogConfig:TicketCreate"],
                TicketInentity = Configuration["LogConfig:TicketInentity"],
                TicketError = Configuration["LogConfig:TicketError"]
            });
            #endregion

 

八、使用方法debug

Logger.Default.Process("具體的錯誤信息", Logger.IdentityGovernmentAffairs);
第一個參數是錯誤信息,第二個參數是寫入的地址
 
 
最終的日誌位置在項目的debug文件下netcore2.2下面的logs文件夾裏面,會有配置文件的地址
 
ok,很久沒更新博客了,下一步會 https://gitee.com/feiyit/FytSoaCms項目作文檔編寫
關注我,和小夥伴們在NetCore的代碼裏一塊兒騷起來
羣號:858895405,一羣心裏騷動的小青年
相關文章
相關標籤/搜索