close

今天來介紹 C# 強大的Nlog 使用方式,來做個筆記 以免自己忘記

Step1:NLog.config 設定 (1)寫入目標 (2)檔案輸出位置 (3)紀錄規則

 

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">


  <variable name="myvar" value="myvalue"/>
  <!--[變數] 文字樣板 -->
  <variable name="Layout" value="${longdate} | ${level:uppercase=true} | ${logger} | ${message} ${newline}"/>
  <variable name="LayoutFatal" value="${longdate} | ${level:uppercase=true} | ${logger} | ${message} | ${exception:format=tostring} ${newline}"/>

  <!--[變數] 檔案位置 -->
  <variable name="LogTxtDir" value="${basedir}/Logs/${shortdate}/"/>
  <variable name="LogTxtLocation" value="${LogTxtDir}/${logger}.log"/>
  <variable name="LogTxtLocationFatal" value="${LogTxtDir}/ERRORFile.log"/>  
  
<!--[設定] 寫入目標-->
  <targets>
    <target name="File" xsi:type="File" fileName="${LogTxtLocation}" layout="${Layout}"
            encoding="utf-8" maxArchiveFiles="30" archiveNumbering="Sequence"
            archiveAboveSize="1048576" archiveFileName="${LogTxtDir}/${logger}.txt{#######}" />
    <target name="FileFatal" xsi:type="File" fileName="${LogTxtLocationFatal}" layout="${LayoutFatal}"
[only the first 25 lines shown in this example]

 

 

Step2:引用方式

內部程式  -宣告

private static Logger Logger = NLog.LogManager.GetCurrentClassLogger();

 

內部程式  -使用Error

try{

}catch(Exception ex){

    MessageBox.Show(ex.Message, "訊息", MessageBoxButtons.OK, MessageBoxIcon.Error);
    Logger.Error(ex.StackTrace.ToString());

}

 

內部程式 -使用Trace

 Logger.Trace(" -------------------------------- Logger Start --------------------------------");

 

大概這樣~~~以上有問題歡迎留言指教 謝謝各位

全站熱搜
創作者介紹
創作者 小蟻蟻 的頭像
小蟻蟻

android飯粒&小小工程師旅遊生活

小蟻蟻 發表在 痞客邦 留言(0) 人氣()