2017年8月1日 星期二

[C#]NuGet - Info and Configuration-API for NLog


  • 安裝 Nlog
  • 專案檔中會有下列兩個檔案
    • NLog.config
    • NLog.xsd
  • NLog.config 資訊
    • targets
      1. 定義 Log 要存放的 type 為何
      2. 定義 Log 內容格式
      3. 可設定多組 target 
    • rules
      1. 定義各種 Level 的 Log 處理方式
      2. 依據各種 Level 定義使用哪個 target 存放資料
      3. 可設定多組 rules
  • Targets [設定] 寫入目標
    • Code
    
    < 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.
        (1)
        NLog package (xsi:type="File")
        https://github.com/NLog/NLog/wiki/Targets
        ColoredConsole - Writes log messages to the console with customizable coloring.
        Console - Writes log messages to the console.
        Database - Writes log messages to the database using an ADO.NET provider.
        EventLog - Writes log message to the Event Log.
        File - Writes log messages to one or more files.
        Mail - Sends log messages by email using SMTP protocol.
        NLogViewer - Sends log messages to the remote instance of NLog Viewer.
        OutputDebugString - Outputs log messages through the OutputDebugString() Win32 API.
        
        (2)
        name – target name
    
        (3)
        Layout Renderers (layout="${longdate} ${uppercase:${level}} ${message}")
        https://github.com/NLog/NLog/wiki/Layout-renderers
        ${basedir}–應用程式所在的資料庫
        ${callsite}–日誌來源的類別名稱、方法名稱和來源資訊
        ${date}–目前日期和時間
        ${onexception}–例外的訊息
        ${level}–日誌的級別
        ${logger}–日誌的來源
        ${longdate}–長日期格式 yyyy-MM-dd HH:mm:ss.mmm
        ${machinename}–電腦名稱
        ${message}–日誌的內容
        ${newline}–換行符號
        ${shortdate}–短日期格式 yyyy-MM-dd
        ${stacktrace}–呼叫堆疊資訊
        ${windows-identity}–登入帳號
        */
    
        /* Sample 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}" />
        
      < /targets>
    
  • Rules [設定] 紀錄規則
    • Code
    
      < rules>   
        /* 
        add your logging rules here
        
        Log element (minlevel="Debug")
        NLog 可以使用的屬性
        https://github.com/NLog/NLog/wiki/Configuration-file#Rules
        (1)
        name–日誌來源的名稱(允許使用通配符號*)
        
        (2)
        level–設定符合該規則的特定級別
        levels–設定符合該規則的級別列表,用逗號分隔
        minlevel–設定符合該規則的最低級別
        maxlevel–設定符合該規則的最高級別
        (2*)
        The level related keywords are processed in the following order:
        1. level
        2. levels
        3. minlevel and maxlevel (minimum and maximum level keywords have the same priority)
        4. No keyword (All levels are logged)
        (2**)
        log level (minlevel="Debug")
        NLog 日誌級別分為六個等級,方便對於不同情境制訂出合適級別輸出
        https://github.com/NLog/NLog/wiki/Configuration-file#log-levels
        Fatal–致命錯誤的訊息,通常會造成應用程式無法執行
        Error–一般錯誤的訊息,一般就是try catch到的Exception
        Info–用來提示用的訊息,例如使用者登出入,交易參數資料
        Warn–用來警告用的訊息,例如執行時間超出預期,連線數接近上限
        Debug–用來除錯用的詳細訊息,比Trace用的少一點,一般也只用在開發環境
        Trace–大量而詳細的訊息,一般只用在開發環境
        
        (3)
        writeTo–設定符合該規則的日誌要寫入的target列表,用逗號分隔
        final–設定符合該規則的條件為最後一個規則,後面的規則不再檢查
        enabled–Disabled rules are ignored
        */
    
        /* 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" />
    
      < /rules>
    
  • Using  NLog
    • Code
    
                // Using NLog.config Info
                NLog.Logger logger = LogManager.GetCurrentClassLogger();
                logger.Info("Info Lyndon");
                logger.Error("Error Demo");
  • Configuration-API
  • 
                // Sample: https://github.com/nlog/NLog/wiki/Configuration-API
                // Step 1. Create configuration object 
                LoggingConfiguration config = new LoggingConfiguration();
    
                // Step 2. Create targets and add them to the configuration 
                FileTarget fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);
    
                // Step 3. Set target properties 
                fileTarget.FileName = "${basedir}/logs/${shortdate}Demo.log";
                fileTarget.Layout = "${longdate} | ${callsite} | ${uppercase:${level}} | ${message}";
    
                // Step 4. Define rules
                LoggingRule rule = new LoggingRule("*", LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule);
    
                // Step 5. Activate the configuration
                LogManager.Configuration = config;
    
                // Example usage
                Logger logger = LogManager.GetLogger("DemoExample");
                logger.Trace("trace log message");
                logger.Debug("debug log message");
                logger.Info("info log message");
                logger.Warn("warn log message");
                logger.Error("error log message");
                logger.Fatal("fatal log message");
    
    • 此方法會將原本的 config 資訊給取代掉,因此原本 config 資訊將不動作
  • Add Target and Rule
    • 此方法可以延用原本的 config ,並加上新增加的 Target 與 Rule
    • Code
    
                // Sample: https://github.com/nlog/NLog/wiki/Configuration-API
                // Step 1. Create configuration object 
                //LoggingConfiguration config = new LoggingConfiguration();
    
                // Step 2. Create targets and add them to the configuration 
                FileTarget fileTarget = new FileTarget();
                LogManager.Configuration.AddTarget("file", fileTarget);
    
                // Step 3. Set target properties 
                fileTarget.FileName = "${basedir}/logs/${shortdate}Demo.log";
                fileTarget.Layout = "${longdate} | ${callsite} | ${uppercase:${level}} | ${message}";
    
                // Step 4. Define rules
                LoggingRule rule = new LoggingRule("NLogAPConfigILib", LogLevel.Debug, fileTarget);
                //config.LoggingRules.Add(rule);
                LogManager.Configuration.LoggingRules.Add(rule);
                // *** Reload
                LogManager.Configuration.Reload();
    
                // Step 5. Activate the configuration
                //LogManager.Configuration = config;
    
                // Example usage
                Logger logger = LogManager.GetLogger("NLogAPConfigILib");
                logger.Trace("trace log message");
                logger.Debug("debug log message");
                logger.Info("info log message");
                logger.Warn("warn log message");
                logger.Error("error log message");
                logger.Fatal("fatal log message");
    
    • 加入 Target 與 Rules,一定要呼叫 LogManager.Configuration.Reload()
  • variable [變數] 文字樣板
    • 當有相同的 layout,可將參數設定至此
    • Code (Before)
    
      < variable name="myvar" value="myvalue"/>
      
      < targets>
        < target 
          xsi:type="File" 
          name="f" 
          fileName="${basedir}/logs/${shortdate}.log"
          layout="${longdate} ${uppercase:${level}} ${message}" />
      < /targets>
    
      < rules>   
        < logger name="NLogLib" minlevel="Debug" writeTo="f" />
      < /rules>
    
    • Code (After)
    
      < variable name="DemoLayout" value="${longdate} ${uppercase:${level}} ${message}"/>
      
      < targets>
        < target 
          xsi:type="File" 
          name="f" 
          fileName="${basedir}/logs/${shortdate}.log"
          layout="${DemoLayout}" />
      < /targets>
    
      < rules>   
        < logger name="NLogLib" minlevel="Debug" writeTo="f" />
      < /rules>
  • Ref:
    • https://dotblogs.com.tw/wasichris/2015/02/27/150582
    • https://stackoverflow.com/questions/7471490/add-enable-and-disable-nlog-loggers-programmatically
    • http://blog.developer.idv.tw/2012/12/nlog-rules.html
    • https://xianlee.gitbooks.io/csharp/content/nlog/index.html
    • http://www.jianshu.com/p/0059a69da89e
    • https://jeffprogrammer.wordpress.com/2015/12/13/asp-net-mvc-%E7%B0%A1%E6%98%93%E4%BD%BF%E7%94%A8-nlog-%E6%8D%95%E6%8D%89%E7%95%B0%E5%B8%B8%E7%8B%80%E6%B3%81/
    • https://dotblogs.com.tw/jwpl102216/2017/03/26/090338
    • http://ithelp.ithome.com.tw/articles/10138479
    • http://blog.darkthread.net/post-2016-05-16-nlog-trouble-shooting.aspx
    • https://xianlee.gitbooks.io/csharp/content/nlog/index.html
    • http://ithelp.ithome.com.tw/articles/10138479
    • https://dotblogs.com.tw/jwpl102216/2017/03/26/090338
    • https://jeffprogrammer.wordpress.com/2015/12/13/asp-net-mvc-%E7%B0%A1%E6%98%93%E4%BD%BF%E7%94%A8-nlog-%E6%8D%95%E6%8D%89%E7%95%B0%E5%B8%B8%E7%8B%80%E6%B3%81/

沒有留言:

張貼留言