承接上篇,NLog的紀錄可以改寫到資料庫中的,另外Nlog.config檔案也可以與Web.config合併喔,首先進行合併,把Nlog.config的內容除了<?xml….utf-8″?>不要複製外,把內容貼到Web.config的</configuration>之前,然後跑跑看測試,當然跑不出來囉,這是因為Web.config不認識nlog的標籤,只要在<configSections>標籤下多加入一個<section即可,如下:

<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>

這樣就可以運作了,不過記得資料庫要開Table,語法如下:

  SET ANSI_NULLS ON
  SET QUOTED_IDENTIFIER ON
  CREATE TABLE [dbo].[NLog] (
	  [Id] [int] IDENTITY(1,1) NOT NULL,
	  [MachineName] [nvarchar](50) NOT NULL,
	  [Logged] [datetime] NOT NULL,
	  [Level] [nvarchar](50) NOT NULL,
	  [Message] [nvarchar](max) NOT NULL,
	  [Logger] [nvarchar](250) NULL,
	  [Callsite] [nvarchar](max) NULL,
	  [Exception] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.Log] PRIMARY KEY CLUSTERED ([Id] ASC)
      WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
  ) ON [PRIMARY]

<nlog></nlog>標籤內容可以參考如下,重要的是connectionStringName要改成既有的資料庫連線,NLog.xsd位置也可以換掉。

  <!-- 啟用Log -->
  <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 Content/NLog.xsd"
        autoReload="true"
        throwExceptions="false"
        internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
    <targets>
      <target xsi:type="File" name="f" fileName="${basedir}/App_Data/logs/${shortdate}.log"
              layout="${longdate} ${uppercase:${level}} ${message}" />
      <target name="database" xsi:type="Database" connectionStringName="您的資料庫連線名稱">
        <commandText>INSERT INTO dbo.NLog (MachineName, Logged, Level, Message,Logger, Callsite, Exception) VALUES (@MachineName, @Logged, @Level, @Message,@Logger, @Callsite, @Exception);</commandText>
        <parameter name="@MachineName" layout="${machinename}" />
        <parameter name="@Logged" layout="${date}" />
        <parameter name="@Level" layout="${level}" />
        <parameter name="@Message" layout="${message}" />
        <parameter name="@Logger" layout="${logger}" />
        <parameter name="@Callsite" layout="${callsite}" />
        <parameter name="@Exception" layout="${exception:tostring}" />
      </target>
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" writeTo="f" />
      <logger name="*" minlevel="Debug" writeTo="database" />
    </rules>
  </nlog>

完成後,這個範例既會寫檔案log,也會寫資料庫log。

LEAVE A REPLY

Please enter your comment!
Please enter your name here