NLog.Database
從 NLog 5.0,Database 功能變成獨立套件 - NLog.Database,找到的範例都只要安裝 NLog 主套件就可以使用 DatabaseTarget,後來才在官網上找到說明 (下圖),namespace 還是維持在 NLog.Targets 內
提供簡單 Target 和 Rule 設定方式,該設定方式只能設定一個 Target,且會覆蓋現有的 config 喔
SimpleLayout 是屬於 plain text Layout 為預設 Layout,輸入 Layout 資訊時不需要特別去指定
紀錄 Text 和兩種 Store Procedure 呼叫的使用方式
建立對應的 LogTable 和 Store Procedure
USE [AdventureWorks2019]
GO
CREATE TABLE [dbo].[LogTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[LogTime] [datetime] NULL,
[Message] [nvarchar](4000) NULL,
CONSTRAINT [PK_LogTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE PROCEDURE [dbo].[uspLogInsert]
(
@LogTime datetime ,
@Message nvarchar(4000)
)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO LogTable (LogTime , Message)
VALUES(@LogTime , @Message)
END
GO
C# 相關語法
using NLog;
using NLog.Layouts;
using NLog.Targets;
using NLog.Config;
using System;
namespace NLogSample
{
internal class Program
{
// 透過 LogManager.GetCurrentClassLogger() 取得 NLog 設定檔
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
DatabaseConfig();
try
{
ExceptionMethod();
}
catch (Exception ex)
{
_logger.Error(ex);
}
}
private static void ExceptionMethod()
{
int numerator = 1;
int denominator = 0;
Console.WriteLine(numerator / denominator);
}
private static void DatabaseConfig()
{
DatabaseTarget target = new DatabaseTarget();
// 連結本機 SQL Server 來測試
target.ConnectionString = "Data Source=.;Initial Catalog=AdventureWorks2019;Integrated Security=True";
// 方法一:利用 Text 輸入 insert 語法
target.CommandText = "insert into LogTable(LogTime,Message) values(@LogTime, @Message);";
// 方法二:呼叫 Store Procedure 來進行 insert
target.CommandType = CommandType.StoredProcedure;
target.CommandText = "uspLogInsert";
// 方法三:呼叫 Store Procedure 來進行 insert
target.CommandText = "exec uspLogInsert @LogTime , @Message";
// 故意用兩種方式來記錄參數設定
target.Parameters.Add(new DatabaseParameterInfo() { Name = "@LogTime", Layout = "${date}" });
target.Parameters.Add(new DatabaseParameterInfo("@Message", new SimpleLayout("${exception}")));
SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
}
}
}
執行結果
沒有留言:
張貼留言