2014年9月18日 星期四

NLog Database Target

NLog要把Log存到資料庫的話,可以透過Database這個taget

<?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">
    <targets>
        <target xsi:type="Database" name="db"
                connectionString="data source=(localdb)\v11.0;database=LogDB; trusted_connection=true;"
                commandText="INSERT INTO NLog_Error(ThreadId, MachineName, LogName, LogLevel, LogMessage, CallSite, Exception, Stacktrace) VALUES (@ThreadId, @MachineName, @LogName, @LogLevel, @LogMessage, @CallSite, @Exception, @Stacktrace);">
            <parameter name="@ThreadId" layout="${threadid}"/>
            <parameter name="@MachineName" layout="${machinename}"/>
            <parameter name="@LogName" layout="${logger}"/>
            <parameter name="@LogLevel" layout="${level}"/>
            <parameter name="@LogMessage" layout="${message}"/>
            <parameter name="@CallSite" layout="${callsite:filename=true}"/>
            <parameter name="@Exception" layout="${exception}"/>
            <parameter name="@stacktrace" layout="${stacktrace}"/>
        </target>
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="db" />
    </rules>
</nlog>


資料庫的Table Schema

USE LogDB
GO

IF OBJECT_ID('NLog_Error') IS NOT NULL
DROP TABLE NLog_Error
GO

CREATE TABLE NLog_Error
(
 LogId   INT    NOT NULL IDENTITY(1,1) PRIMARY KEY,
 ThreadId  INT    NOT NULL,
 MachineName  VARCHAR(255) NOT NULL,
 LogName   VARCHAR(255) NOT NULL,
 LogLevel  VARCHAR(5)  NOT NULL,
 LogMessage  VARCHAR(MAX) NOT NULL,
 CallSite  VARCHAR(1024) NOT NULL,
 Exception  VARCHAR(1024) NOT NULL,
 Stacktrace  VARCHAR(1024) NOT NULL,
 CreateDateTime DATETIME NOT NULL DEFAULT(GETDATE())
)
GO