CJF.Utilities.Logger
1.22.412
dotnet add package CJF.Utilities.Logger --version 1.22.412
NuGet\Install-Package CJF.Utilities.Logger -Version 1.22.412
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CJF.Utilities.Logger" Version="1.22.412" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CJF.Utilities.Logger" Version="1.22.412" />
<PackageReference Include="CJF.Utilities.Logger" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CJF.Utilities.Logger --version 1.22.412
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: CJF.Utilities.Logger, 1.22.412"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CJF.Utilities.Logger@1.22.412
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CJF.Utilities.Logger&version=1.22.412
#tool nuget:?package=CJF.Utilities.Logger&version=1.22.412
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
CJF.Utilities.Logger
這是一個提供多種記錄器實作的函式庫,包含檔案記錄器、資料庫記錄器和自訂主控台格式器,適用於 Microsoft.Extensions.Logging 框架。
版本資訊
- 版本: 1.22.412
- 作者: Chen Jaofeng
- 建立日期: 2025-05-17
- 相容性: .NET 8.0 以上
- 相依套件: Microsoft.Data.SqlClient (6.0.1), Microsoft.Extensions.Logging.Console (9.0.3)
主要功能
FileLogger (檔案記錄器)
- 自動檔案管理:依日期自動建立記錄檔
- 檔案大小控制:超過指定大小自動分割檔案
- 自訂格式:支援彈性的訊息格式設定
- 範圍支援:支援記錄範圍 (Scope) 功能
- ANSI 碼過濾:自動移除主控台顏色碼
DbEventLogger (資料庫記錄器)
- SQL Server 支援:將記錄寫入 SQL Server 資料庫
- 彈性欄位對應:可自訂資料庫欄位對應
- 自訂 SQL 腳本:支援自訂 INSERT 語句
- 錯誤處理:資料庫連線失敗時的錯誤處理
CustomConsoleFormatter (自訂主控台格式器)
- 彈性格式設定:可設定前置/後置字串
- EventId 過濾:可忽略特定 EventId 的訊息
- 時間戳記格式:支援自訂時間格式
- 範圍顯示:支援記錄範圍的顯示
相依套件
- Microsoft.Data.SqlClient (6.0.1)
- Microsoft.Extensions.Logging.Console (9.0.3)
安裝方式
dotnet add package CJF.Utilities.Logger
使用範例
方法一:直接使用
var builder = WebApplication.CreateBuilder(args)
.ConfigureLogging((context, logging) => {
// 清除預設的記錄提供者
logging.ClearProviders();
// 使用預設主控台記錄器,但指定自訂格式器
logging.AddConsole(opts => opts.FormatterName = nameof(CustomConsoleFormatter));
logging.AddConsoleFormatter<CustomConsoleFormatter, CustomConsoleOptions>(opts =>
{
opts.Prefix = "[MyApp]";
opts.Suffix = "END";
opts.TimestampFormat = "HH:mm:ss.fff";
opts.IngoreIDs = new[] { 1001, 1002 }; // 忽略特定 EventId
});
// 使用檔案記錄器
logging.AddFileLogger(opts => {
opts.SavePath = "./logs/";
opts.FilePattern = "app_{yyyy-MM-dd}.log";
opts.MaxFileSize = 50; // 50 MB
opts.MsgPattern = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Category[^1]}: {Message}{NewLine}{Exception}";
});
// 使用資料庫記錄器
logging.AddDbLogger(opts => {
opts.Connection = new DbConnection
{
Server = "localhost",
Database = "LogDB",
UserId = "db_user_login_id",
Password = "encrypted_password",
SecretKey = "_Key_Key", // 用來解密密碼,8 Bytes
InitVector = "00000000" // 用來解密密碼,8 Bytes
};
opts.Script = "INSERT INTO [dbo].[TB_EventLog] (LogTime, Level, EventId, Category, Tag, Message) VALUES (@Time, @Level, @Event, @Category, @Tag, @Msg)";
opts.Fields = new List<DbLoggerField>
{
new() { Name = "@Time", Field = "Timestamp" },
new() { Name = "@Level", Field = "Level", Size = 5 },
new() { Name = "@Event", Field = "EventId" },
new() { Name = "@Category", Field = "Category[^1]", Size = 64 },
new() { Name = "@Tag", Field = "Scope", Size = 64 },
new() { Name = "@MSG", Field = "Message", Size = 2048 }
};
});
});
方法二:使用 appsettings.json
appsettings.json
設定
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
},
"ConsoleFormatterOptions": {
"Prefix": "[MyApp]",
"Suffix": "END",
"TimestampFormat": "HH:mm:ss.fff",
"IngoreIDs": [1001, 1002]
},
"FileLogger": {
"LogLevel": {
"Default": "Information",
},
"Options": {
"SavePath": "./logs/",
"FilePattern": "log_{yyyy-MM-dd}.txt",
"MaxFileSize": 100,
"MsgPattern": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} - {Level,-5} [{Category[^1]}] {Message}{NewLine}{Exception}"
}
},
"DbLogger": {
"LogLevel": {
"Default": "Information"
},
"Options": {
"Connection": {
"Server": "localhost",
"Database": "LogDB",
"UserId": "db_user_login_id",
"Password": "encrypted_password"
},
"Script": "INSERT INTO [dbo].[TB_EventLog] (LogTime, Level, EventId, Category, Tag, Message) VALUES (@Time, @Level, @Event, @Category, @Tag, @Msg)",
"Fields": [
{
"Name": "@Time",
"Field": "Timestamp"
},
{
"Name": "@Level",
"Field": "Level",
"Size": 5
},
{
"Name": "@Event",
"Field": "EventId"
},
{
"Name": "@Category",
"Field": "Category[^1]",
"Size": 64
},
{
"Name": "@Tag",
"Field": "Scope",
"Size": 64
},
{
"Name": "@MSG",
"Field": "Message",
"Size": 2048
}
]
}
}
}
}
- 在
Program.cs
中載入設定
var builder = WebApplication.CreateBuilder(args)
.ConfigureLogging((context, logging) => {
// 清除預設的記錄提供者
logging.ClearProviders();
// 使用預設主控台記錄器,但指定自訂格式器
logging.AddConsole(opts => opts.FormatterName = nameof(CustomConsoleFormatter));
logging.AddConsoleFormatter<CustomConsoleFormatter, CustomConsoleOptions>(opts =>
builder.Configuration.GetSection("Logging:ConsoleFormatterOptions").Bind(opts));
// 使用檔案記錄器
logging.AddFileLogger(opts => builder.Configuration.GetSection("Logging:FileLogger:Options").Bind(opts));
// 使用資料庫記錄器
logging.AddDbLogger(opts => builder.Configuration.GetSection("Logging:DbLogger:Options").Bind(opts));
});
設定選項
FileLoggerOptions
屬性 | 型別 | 預設值 | 說明 |
---|---|---|---|
SavePath | string | "./logs/" | 記錄檔儲存路徑 |
FilePattern | string | "log_{yyyy-MM-dd}.txt" | 檔案名稱格式 |
MaxFileSize | int | 100 | 檔案最大大小 (MB) |
MsgPattern | string | 複雜格式 | 訊息格式樣板 |
DbLoggerOptions
屬性 | 型別 | 說明 | 備註 |
---|---|---|---|
ConnectionString | string | SQL Server 連線字串 | |
Connection | DbConnection | 資料庫連線資訊 | 使用加密的連線資訊 |
Script | string | INSERT SQL 腳本 | |
Fields | List<DbLoggerField> | 欄位對應設定 |
CustomConsoleOptions
屬性 | 型別 | 預設值 | 說明 |
---|---|---|---|
Prefix | string | null | 訊息前置字串 |
Suffix | string | null | 訊息後置字串 |
IngoreIDs | int[] | null | 忽略的 EventId 陣列 |
TimestampFormat | string | null | 時間戳記格式 |
DbLoggerField
屬性 | 型別 | 說明 | 備註 |
---|---|---|---|
Name | string | SQL 參數名稱 | |
Field | string | 對應的記錄欄位 | 請參閱資料庫欄位對應 |
Size | int? | 欄位大小 (可選) |
DbConnection
屬性 | 型別 | 說明 | 備註 |
---|---|---|---|
Server | string | SQL Server 主機名稱 | |
Database | string | 資料庫名稱 | |
UserId | string | 使用者 ID | |
Password | string | 加密的密碼 | 使用 DES 加密,需提供 SecretKey 和 InitVector |
SecretKey | string | 用於解密密碼的金鑰 (8 Bytes) | 建議在程式內指定 |
InitVector | string | 用於解密密碼的初始向量 (8 Bytes) | 建議在程式內指定 |
訊息格式樣板
FileLogger Message Pattern 支援以下格式標記:
{Timestamp:format}
- 時間戳記{Level}
- 記錄層級{Category}
- 記錄來源類別{Category[^1]}
- 類別名稱(不含命名空間){Scope}
- 記錄範圍{Message}
- 記錄訊息{Exception}
- 例外資訊{NewLine}
- 新行字元{ThreadId}
- 執行緒 ID{EvtId}
- 事件 ID{EvtName}
- 事件名稱
資料庫欄位對應
DbLoggerField 支援以下欄位:
Category
- 記錄來源類別Category[^1]
- 類別名稱(不含命名空間)EventId
- 事件 IDEventName
- 事件名稱Level
- 記錄層級Message
- 記錄訊息Scope
- 記錄範圍ThreadId
- 執行緒 IDTimestamp
- 時間戳記
注意事項
- 檔案記錄器會自動建立目錄
- 資料庫記錄器需要預先建立資料表
- 所有記錄器都會自動過濾 ANSI 顏色碼
- 支援記錄範圍 (Scope) 功能
- 執行緒安全設計
版本歷程
v1.22.412 (2025-08-12)
- 修改
FileLogger
和DbEventLogger
類別標記為 partial,並使用 GeneratedRegex 特性優化正則表達式的性能 - 新增
DbEventLogger
的Connection
屬性,使用加密的連線資訊 DbLoggerField.Field
屬性新增Category[^1]
語法,將會以.
分割字串並取得陣列的最後一個字串
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- Microsoft.Data.SqlClient (>= 6.0.1)
- Microsoft.Extensions.Logging.Console (>= 9.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
### v1.22.412 (2025-08-12)
- 修改 `FileLogger` 和 `DbEventLogger` 類別標記為 partial,並使用 GeneratedRegex 特性優化正則表達式的性能
- 新增 `DbEventLogger` 的 `Connection` 屬性,使用加密的連線資訊
- `DbLoggerField.Field` 屬性新增 `Category[^1]` 語法,將會以 `.` 分割字串並取得陣列的最後一個字串