C# 使用NLog記錄日誌入門操做

 環境:win7 64位, VS2010git

一、首先用VS2010建立命令行工程NLogDemogithub

二、在程序包管理器控制檯中輸入:Install-Package NLog -Version 4.4.12session

  這句是怎麼來的,要是你用過nuget包管理工具,那就能夠跳過這裏的說明了。app

  要使用nuget添加NLog包到項目中。請看下圖。dom

 

而後在程序包管理工具控制檯下輸入:Install-Package NLog -Version 4.4.12工具

再看看Install-Package NLog -Version 4.4.12這個怎麼找。spa

打開百度搜索:Nuget.net

而後在Nuget官網上搜索欄輸入:Nlog 回車命令行

選擇第一項Nlog3d

 

而後在 Version History 下選擇 4.4.12 這個版本

 

至於爲何選擇這個版本,由於這個版本下載的次數多。嘿嘿,沒辦法,隨大流。固然還要看這個版本包的依賴項

這個包的沒有什麼特殊依賴項,因此能夠使用。而後拷貝

 

 

 這裏這句話就是要咱們要找的。是否是挺簡單的。

當咱們在包程序包管理器控制檯中輸入:Install-Package NLog -Version 4.4.12 而後按下回車鍵,VS IDE 會自動到 nuget.org 這裏下載依賴包。

NLog 包添加完以後,還要添加 NLog.config(4.4.12)(Install-Package NLog.Config -Version 4.4.12) 這個包,按道理 NLog 和 NLog.config 應該一塊兒的,

忽然從某個版本開始分開了,要單獨添加。具體狀況能夠去官網看介紹:https://nlog-project.org/

 

添加 NLog.config 的方法跟上面添加 NLog 的方法同樣。

三、簡單封裝 Log

  添加類Log.cs到工程中,修改代碼以下:

public sealed class Log
{
    private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

    private Log() { }

    public static void Trace(string strMsg)
    {
        _logger.Trace(strMsg);
    }

    public static void Debug(string strMsg)
    {
        _logger.Debug(strMsg);
    }

    public static void Info(string strMsg)
    {
        _logger.Info(strMsg);
    }

    public static void Warn(string strMsg)
    {
        _logger.Warn(strMsg);
    }

    public static void Error(string strMsg)
    {
        _logger.Error(strMsg);
    }

    public static void Fatal(string strMsg)
    {
        _logger.Fatal(strMsg);
    }

}

四、修改NLog.config文件,具體內容以下:

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

  <!-- optional, add some variables
  https://github.com/nlog/NLog/wiki/Configuration-file#variables
  -->
    <!--
  <variable name="myvar" value="myvalue"/>
    -->
    <variable name="fileFormat"
            value="
            ${newline}date: ${date}
            ${newline}level: ${level}
            ${newline}logger: ${logger}
            ${newline}machinename: ${machinename}
            ${newline}message: ${message}
            ${newline}appdomain: ${appdomain}
            ${newline}assembly-version: ${assembly-version}
            ${newline}basedir: ${basedir}
            ${newline}callsite: ${callsite}
            ${newline}counter: ${counter}
            ${newline}nlogdir: ${nlogdir}
            ${newline}processid: ${processid}
            ${newline}processname: ${processname}
            ${newline}specialfolder: ${specialfolder}
            ${newline}stacktrace: ${stacktrace}
            ${newline}------------------------------------------------------------" />

  <!--
  See https://github.com/nlog/nlog/wiki/Configuration-file
  for information on customizing logging rules and outputs.
   -->
  <targets>

    <!--
    add your targets here
    See https://github.com/nlog/NLog/wiki/Targets for possible targets.
    See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
    -->

    <!--
    Write events to a file with the date in the filename.
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
    -->

      <target name="file" xsi:type="File"
            fileName="${basedir}/Logs/${date:format=yyyy-MM}/${shortdate}.log"
            layout="${fileFormat}"
            maxArchiveFiles="5"
            archiveAboveSize="10240" />
      
  </targets>

  <rules>
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->

    <!--
        Level    Example
        Fatal    Highest level: important stuff down
        Error    For example application crashes / exceptions.
        Warn    Incorrect behavior but the application can continue
        Info    Normal behavior like mail sent, user updated profile etc.
        Debug    Executed queries, user authenticated, session expired
        Trace    Begin method X, end method X etc
    -->
    <!--
        Logging 水平分爲如下等級「Trace<<Debug<<Info<<Warn<<Error<<Fatal 」,若是咱們選擇Info值,則Trace和Debug等級的信息不會被輸出。
    -->
     <logger name="*" minlevel="Trace" writeTo="file"/>
  </rules>
</nlog>

簡單解釋:

variable  log文件的內容輸出格式
targets 目標文件(要生成的Log文件)的配置(文件名、格式變量、文件個數、文件大小等等)
rules 規則,也就是俗話說的Log輸出級別

以上內容不進行過多解釋了,再多解釋也不如官網的說明。詳細介紹請看官網:https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-format

更多配置文件能夠參考: https://github.com/jkowalski/NLog/tree/master/examples/targets/Configuration%20File

五、使用Log輸出日誌到文件,簡單示例代碼以下

class Program
{
    static void Main(string[] args)
    {
        RunTest();
        
        Console.WriteLine("Press a key end ...");
        Console.ReadKey(true);
    }

    static void RunTest()
    {
        for (int i = 0; i < 1000; i++)
        {
            Log.Info(string.Format("{0}", i + 1));

            System.Threading.Thread.Sleep(10);
        }
    }

}

輸出路徑結構

輸出文件內容:

以上內容輸出格式能夠在NLog.config中根據需求進行裁剪。

demo下載

相關文章
相關標籤/搜索