NLog已是平日寫.NET專案的標準配備(另一個是Json.NET,每個專案都要加,恨不得.NET能把它納入內建),但偶爾需要確認Log檔路徑(不確定NLog.config寫法是否有錯,設定是否生效),每次遇到每次重新爬文,記性之差,讓網友直呼太誇張,只好寫篇筆記救救自己。

例如有NLog.config寫法如下:(順便筆記我最常用的NLog檔案設定樣式)

<?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"> 
  <targets> 
    <target xsi:type="File" name="f" fileName="e:/AfaConsoleLog/${logger}/${shortdate}.log" 
            layout="${longdate} ${uppercase:${level}} ${message}" /> 
  </targets> 
  <rules> 
    <logger name="*" minlevel="Debug" writeTo="f" /> 
  </rules> 
</nlog>

要取得f Target產生的檔案路徑,做法是先用FindTargetByName取得 f Target轉型為FileTarget型別,但由於Log檔路徑與Logger名稱及日期有關,故要用FileName.Render()傳入日期及Logger名稱參數才能得到結果。以上可濃縮成一行:

(LogManager.Configuration.FindTargetByName("f") as NLog.Targets.FileTarget).FileName
.Render(new LogEventInfo() { TimeStamp = DateTime.Now, LoggerName = "loggerName" })

趁著偵錯中斷,丟進Visual Studio的立即執行視窗可當場取值,例如:"e:/AfaConsoleLog/loggerName/2015-12-08.log"

若要省事,可以寫成共用函式丟進通用程式庫,呼叫方法可再簡化為 MyUtility.ProbeNLogFilePath("f");

/// <summary>
/// 偵測NLog檔案路徑及名稱 REF: http://stackoverflow.com/a/11629408
/// </summary>
/// <param name="targetName">目標名稱</param>
/// <param name="loggerName">Logger名稱</param>
/// <returns></returns>
public static string ProbeNLogFilePath(string targetName, string loggerName = "LoggerName")
{     
    return (NLog.LogManager.Configuration.FindTargetByName(targetName) as NLog.Targets.FileTarget)
    .FileName.Render(new LogEventInfo() { TimeStamp = DateTime.Now, LoggerName = loggerName });
}

Comments

# by Akito

我也常忘記路徑怎麼設定Orz (老了嗚嗚嗚嗚嗚) 謝謝大大分享~

Post a comment


83 - 46 =