Nlog 筆記 + Sample

NLog note and sample

NLog.config

需要先用 Nuget 安裝 NLog、NLog.Config 、NLog.Schema 

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

  <!--targets 存放位置與型態...等等-->
  <targets>
    <target
      xsi:type="File"
      fileName="${basedir}/logs/${shortdate}.log"
      layout="${longdate} ${uppercase:${level}} ${message} ${exception}"
      name="ABCDEFG"
      />
  </targets>

  <!--rules 指定 log 等級 -->
  <rules>
    <logger 
      name="*" 
      minlevel="Debug" 
      writeTo="ABCDEFG" />
  </rules>
  
</nlog>

WebForm1.aspx.cs

using NLog;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
 
    public partial class WebForm1 : System.Web.UI.Page
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        protected void Page_Load(object sender, EventArgs e)
        {

            //寫法一
            logger.Trace("Sample trace message");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");

            //寫法二 :  呼叫 Log() method            
            logger.Log(LogLevel.Info, "Sample informational message");

        }
    }

}

Log 等級

如果寫在 web.config / app.config (尚未測試,不確定  ) 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <nlog>

      <!--HERE~~!!-->

  </nlog>
</configuration>

參考資料:

範例:

https://riptutorial.com/nlog

教學:

https://www.itread01.com/content/1544724366.html

https://www.codeproject.com/Articles/10631/Introduction-to-NLog

NLog 參數 API :

http://relycoding.blogspot.com/2017/02/nlog.html