在一些特定場景的業務需求下,日志需要寫入到不同的路徑下提供日志分析。
第一種:默認Nlog可以通過日志級別來區分路徑,
——優點是不需要額外配置,開箱即用
——缺點是不夠靈活,如果超過級別數量,則不滿足需求
第二種:通過定義FileTarget來根據業務寫入不同的地址
廢話不多說了,直接上代碼
1、創建NetCore,並且引入Nlog和NLog.Web.AspNetCore 這個就不介紹和貼圖了
2、創建nlog配置文件
注意配置文件里面的:
<variable name="cuspath" value="" />
相當於根據變量的方式來定義日志輸出目錄
github文檔說明地址:https://github.com/NLog/NLog/wiki/Configuration-file
在輸入文件名稱中加入變量名稱:
fileName="logs/${var:cuspath}nlog-all-${shortdate}.log"
上面,默認是輸出到logs/目錄中
<?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="info"> <!-- enable asp.net core layout renderers --> <extensions> <add assembly="NLog.Web.AspNetCore"/> </extensions> <variable name="cuspath" value="" /> <!-- the targets to write to --> <targets> <!-- write logs to file --> <target xsi:type="File" name="allfile" fileName="logs/${var:cuspath}nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${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="logs/${var:cuspath}nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}|${callsite}" /> </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 --> <logger name="*" minlevel="Trace" writeTo="ownFile-web" /> </rules> </nlog>
3、注冊,在Starup.cs文件中
Configure方法里面注冊下
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } loggerFactory.AddNLog(); env.ConfigureNLog("nlog.config"); app.UseMvc(); }
4、Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseNLog();
5、為了擴展,我們新建一個類來處理日志的寫入
namespace FytSoa.Common { /// <summary> /// 日志模塊 /// </summary> public class Logger { NLog.Logger _logger; private Logger(NLog.Logger logger) { _logger = logger; } public Logger(string name) : this(LogManager.GetLogger(name)) { } /// <summary> /// 單例 /// </summary> public static Logger Default { get; private set; } static Logger() { Default = new Logger(LogManager.GetCurrentClassLogger()); } private static string _path = ""; /// <summary> /// 自定義輸出目錄,初始化 /// </summary> public void Setting(string path) { if (_path != path) { _path = path; LogManager.Configuration.Variables["cuspath"] = path+"/"; } } /// <summary> /// 自定義寫日志路徑 /// </summary> /// <param name="msg">消息</param> /// <param name="path">寫入地址</param> /// <returns></returns> public void Process(string msg, string path="") { _logger.Debug(msg); } #region Debug public void Debug(string msg, params object[] args) { _logger.Debug(msg, args); //LogManager.Shutdown(); } public void Debug(string msg, Exception err) { _logger.Debug(err, msg); //LogManager.Shutdown(); } #endregion #region Info public void Info(string msg, params object[] args) { _logger.Info(msg, args); //LogManager.Shutdown(); } public void Info(string msg, Exception err) { _logger.Info(err, msg); //LogManager.Shutdown(); } #endregion #region Warn public void Warn(string msg, params object[] args) { _logger.Warn(msg, args); //LogManager.Shutdown(); } public void Warn(string msg, Exception err) { _logger.Warn(err, msg); //LogManager.Shutdown(); } #endregion #region Trace public void Trace(string msg, params object[] args) { _logger.Trace(msg, args); //LogManager.Shutdown(); } public void Trace(string msg, Exception err) { _logger.Trace(err, msg); //LogManager.Shutdown(); } #endregion #region Error public void Error(string msg, params object[] args) { _logger.Error(msg, args); //LogManager.Shutdown(); } public void Error(string msg, Exception err) { _logger.Error(err, msg); //LogManager.Shutdown(); } #endregion #region Fatal public void Fatal(string msg, params object[] args) { _logger.Fatal(msg, args); //LogManager.Shutdown(); } public void Fatal(string msg, Exception err) { _logger.Fatal(err, msg); //LogManager.Shutdown(); } #endregion } }
注意:
public void Setting(string path)
方法是設置目錄輸入位置的
6、使用方法
默認輸出到logs文件夾
- Logger.Default.Info("TestDefault"+i);
自定義輸入到其他目錄
- 設置輸出目錄:Logger.Default.Setting("task");
- 調用日志方法:Logger.Default.Setting("task_log");
task_log會輸出到logs/task 文件夾
開源項目NetCore 2.2
https://github.com/feiyit/FytSoaCms page razor方式
NetCore3.1
https://github.com/feiyit/FytSoa3.1 前后端分離
關注我,和小伙伴們在NetCore的代碼里一起騷起來
群號:1060012125,一群內心騷動的小青年