[ASP.net Core] 加入NLog作logger

上篇寫了利用Log4net 做記錄及其現時的限制, 現在會使用NLog 進行記錄. NLog 是一套建於.net 平台的logging framework, 與log4net 比較, 最大好處是NLog的效能比較快及可以concurrent 讀寫, 而log4net 則在programming language 上較廣泛, 可以在相同xml config 下於不同平台執行.

是次示範會在.net Core 中利用NLog 進行檔案及資料庫記錄. 而資料庫則會以SQL server 作示範.

  1. 建立table.
    在SQL Server Management Studio 中執行以下指令.

    /****** Object:  Table [dbo].[system_logging]    Script Date: 04/21/2010 17:05:06 ******/ 
    SET ANSI_NULLS ON 
    GO
    
    SET QUOTED_IDENTIFIER ON 
    GO
    
    SET ANSI_PADDING ON 
    GO
    
    CREATE TABLE [dbo].[Log]( 
        [GUID] [uniqueidentifier] ROWGUIDCOL  NOT NULL, 
        [EnteredAt] [datetime2] NULL, 
        [Application] [varchar](200) NULL, 
        [Date] [varchar](100) NULL, 
        [Level] [varchar](100) NULL, 
        [Logger] [varchar](8000) NULL, 
        [Message] [varchar](8000) NULL, 
        [MachineName] [varchar](8000) NULL, 
        [UserName] [varchar](8000) NULL, 
        [CallSite] [varchar](8000) NULL, 
        [Thread] [varchar](100) NULL, 
        [Exception] [varchar](8000) NULL, 
        [Stacktrace] [varchar](8000) NULL, 
    CONSTRAINT [PK_system_logging] PRIMARY KEY CLUSTERED 
    ( 
        [GUID] ASC 
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY] 
    ) ON [PRIMARY]
    
    GO
    
    SET ANSI_PADDING OFF 
    GO
    
    ALTER TABLE [dbo].[Log] ADD  CONSTRAINT [DF_Log_GUID]  DEFAULT (newid()) FOR [GUID] 
    GO
    
    ALTER TABLE [dbo].[Log] ADD  CONSTRAINT [DF_Log_EnteredAt]  DEFAULT (getdate()) FOR [EnteredAt] 
    GO
  2. 安裝NLog.
    在Package Management Console 中, 輸入以下指令.

    Install-Package NLog
    Install-Package NLog.Config
    Install-Package NLog.Web.AspNetCore
  3. 設定NLog.
    建立XML 檔, 命名為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"
      autoReload="true"
      internalLogLevel="info"
      internalLogFile="C:\log\nlog-internal.txt">
      <targets>
        <!-- write logs to file  -->
        <target xsi:type="File" name="file"
          fileName="C:\log\org.matilda.backend.organization\nlog-all_${shortdate}.log"
          layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger}|${message} ${exception}" />
        
        <target name="database" type="Database">
          <connectionString>
            Data Source=IT-UAT-SVR01\SQLEXPRESS;Initial Catalog=Logging;User Id=AppUser;Password=Nod32;
          </connectionString>
          <commandText>
            insert into [Log]
            (LoggedAt,LogLevel,Logger,Message,MachineName, UserName, CallSite, Thread, Exception, Stacktrace) values
            (@time_stamp, @level, @logger, @message,@machinename, @user_name, @call_site, @threadid, @log_exception, @stacktrace);
          </commandText>
          <parameter name="@time_stamp" layout="${longdate}"/>
          <parameter name="@level" layout="${level}"/>
          <parameter name="@logger" layout="${logger}"/>
          <parameter name="@message" layout="${message}"/>
          <parameter name="@machinename" layout="${machinename}"/>
          <parameter name="@user_name" layout="${windows-identity:domain=true}"/>
          <parameter name="@call_site" layout="${callsite:filename=true}"/>
    
          <parameter name="@threadid" layout="${threadid}"/>
          <parameter name="@log_exception" layout="${exception}"/>
          <parameter name="@stacktrace" layout="${stacktrace}"/>
        </target>
      </targets>
      <rules>
        <logger name="*" minlevel="Trace" writeTo="file" />
        <logger name="*" minlevel="Trace" appendTo="database"/>
      </rules>
    </nlog>
  4. 加入NLog 到Program 中.
    在program.cs 中修改main() 如下.

    public static void Main(string[] args)
            {
                NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
                CreateWebHostBuilder(args).UseStartup<Startup>().UseNLog().Build().Run();
            }
  5. 測試.
    按F5 執行程式, 當見到有記錄檔產生及資料寫入檔案及資料庫, 代表測試成功.
About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.