C#開源日志Nlog入門


   c#語言使用的日志比較多,比如:Log4、NLog等,今天我就簡單隨筆記錄哈NLog的使用。

   1.NLog的安裝:

      直接在VS編譯器中打開程序包管理器,輸入Install-Package NLogin添加進行自己的項目;

      VS程序包管理器請查看 http://blog.csdn.net/doris_d/article/details/46558351

   2.安裝NLog配置文件:

      同上在程序包管理器中加入Install-Package NLogin.config;

   3.添加完成之后,目錄大致如下:

   

    4.打開配置文件進行配置

    

 1 <targets async="true">
 2     <!--
 3     add your targets here
 4     See https://github.com/nlog/NLog/wiki/Targets for possible targets.
 5     See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
 6     -->
 7     <target xsi:type="File" name="file_info"
 8                fileName="${basedir}/Logs/Info/info_${shortdate}.txt"
 9                layout="${message}"
10                archiveAboveSize="10240"
11                archiveNumbering="Sequence"
12                concurrentWrites="true"
13                keepFileOpen="false"
14                encoding="iso-8859-2"
15             />
16     <target xsi:type="File" name="file_debug"
17               fileName="${basedir}/Logs/Debug/debug_${shortdate}.txt"
18               layout="${message}"
19               archiveAboveSize="10240"
20               archiveNumbering="Sequence"
21               concurrentWrites="true"
22               keepFileOpen="false"
23               encoding="iso-8859-2"
24             />
25     <!--
26     Write events to a file with the date in the filename.
27     <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
28             layout="${longdate} ${uppercase:${level}} ${message}" />
29     -->
30   </targets>
31  <rules>
32    <logger name="*" level="Info" writeTo="file_info"></logger>
33    <logger name="*" level="Debug" writeTo="file_debug"></logger>
34 </rules>
View Code

    注意記錄日志有2種方式,同步和異步,只需要再配置targets時候,添加async="true"就為異步,默認為同步。

    target備注:type  類型,日志類型有(保存文件、數據庫);name  名字和下面role規則對應;fileName 文件保存路徑;archiveAboveSize:大小之后會自動添加文件進行保存。

    logger備注:level 日志級別(Info、Debug等) writeTo 同上述名字進行匹配。

   5.進行簡單的測試

    

 1 private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
 2         /// <summary>
 3         /// 寫日志
 4         /// </summary>
 5         /// <param name="action"></param>
 6         public static void WriteDeBug(string address, string msg, string path)
 7         {
 8             ExpectionMsg Entity = new ExpectionMsg()
 9             {
10                 Address = address,
11                 Msg = msg,
12                 Path = path
13             };
14             logger.Debug(Entity.ToString());
15         }
View Code

   6.在config對應的文件中查找文件就好了。

  

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM