CJF.Utilities.Logger 1.22.395

There is a newer version of this package available.
See the version list below for details.
dotnet add package CJF.Utilities.Logger --version 1.22.395
                    
NuGet\Install-Package CJF.Utilities.Logger -Version 1.22.395
                    
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.395" />
                    
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.395" />
                    
Directory.Packages.props
<PackageReference Include="CJF.Utilities.Logger" />
                    
Project file
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.395
                    
#r "nuget: CJF.Utilities.Logger, 1.22.395"
                    
#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.395
                    
#: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.395
                    
Install as a Cake Addin
#tool nuget:?package=CJF.Utilities.Logger&version=1.22.395
                    
Install as a Cake Tool

CJF.Utilities.Logger

NuGet version

這是一個提供多種記錄器實作的函式庫,包含檔案記錄器、資料庫記錄器和自訂主控台格式器,適用於 Microsoft.Extensions.Logging 框架。

版本資訊

  • 版本: 1.22.395
  • 作者: 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 的訊息
  • 時間戳記格式:支援自訂時間格式
  • 範圍顯示:支援記錄範圍的顯示

LogLevelExtensions (記錄層級擴充)

  • 簡短字串轉換:將 LogLevel 轉換為簡短字串表示

相依套件

  • Microsoft.Data.SqlClient (6.0.1)
  • Microsoft.Extensions.Logging.Console (9.0.3)

安裝方式

dotnet add package CJF.Utilities.Logger

使用範例

檔案記錄器

using CJF.Utilities.Logger;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var services = new ServiceCollection();
services.AddLogging(builder =>
{
    builder.AddFileLogger(options =>
    {
        options.SavePath = "./logs/";
        options.FilePattern = "app_{yyyy-MM-dd}.log";
        options.MaxFileSize = 50; // 50 MB
        options.MsgPattern = "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {Category[^1]}: {Message}{NewLine}{Exception}";
    });
});

var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();

logger.LogInformation("應用程式啟動");
logger.LogError("發生錯誤: {Error}", "連線失敗");

資料庫記錄器

using CJF.Utilities.Logger;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var services = new ServiceCollection();
services.AddLogging(builder =>
{
    builder.AddDbLogger(options =>
    {
        options.ConnectionString = "Server=.;Database=LogDB;Integrated Security=true;";
        options.Script = "INSERT INTO Logs (Timestamp, Level, Category, Message, Scope, ThreadId) VALUES (@Timestamp, @Level, @Category, @Message, @Scope, @ThreadId)";
        options.Fields = new List<DbLoggerField>
        {
            new() { Name = "@Timestamp", Field = "Timestamp", Size = 0 },
            new() { Name = "@Level", Field = "Level", Size = 10 },
            new() { Name = "@Category", Field = "Category", Size = 255 },
            new() { Name = "@Message", Field = "Message", Size = 4000 },
            new() { Name = "@Scope", Field = "Scope", Size = 255 },
            new() { Name = "@ThreadId", Field = "ThreadId", Size = 0 }
        };
    });
});

var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();

using (logger.BeginScope("UserLogin"))
{
    logger.LogInformation("使用者 {UserId} 登入成功", 12345);
}

自訂主控台格式器

using CJF.Utilities.Logger;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var services = new ServiceCollection();
services.AddLogging(builder =>
{
    builder.AddConsole(options =>
    {
        options.FormatterName = nameof(CustomConsoleFormatter);
    });
    builder.AddConsoleFormatter<CustomConsoleFormatter, CustomConsoleOptions>(options =>
    {
        options.Prefix = "[MyApp]";
        options.Suffix = "END";
        options.TimestampFormat = "HH:mm:ss.fff";
        options.IngoreIDs = new[] { 1001, 1002 }; // 忽略特定 EventId
    });
});

var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();

logger.LogInformation("這是一個測試訊息");

設定選項

FileLoggerOptions

屬性 型別 預設值 說明
SavePath string "./logs/" 記錄檔儲存路徑
FilePattern string "log_{yyyy-MM-dd}.txt" 檔案名稱格式
MaxFileSize int 100 檔案最大大小 (MB)
MsgPattern string 複雜格式 訊息格式樣板

DbLoggerOptions

屬性 型別 說明
ConnectionString string SQL Server 連線字串
Script string INSERT SQL 腳本
Fields List<DbLoggerField> 欄位對應設定

CustomConsoleOptions

屬性 型別 預設值 說明
Prefix string null 訊息前置字串
Suffix string null 訊息後置字串
IngoreIDs int[] null 忽略的 EventId 陣列
TimestampFormat string null 時間戳記格式

訊息格式樣板

FileLogger 支援以下格式標記:

  • {Timestamp:format} - 時間戳記
  • {Level} - 記錄層級
  • {Category} - 記錄來源類別
  • {Category[^1]} - 類別名稱(不含命名空間)
  • {Scope} - 記錄範圍
  • {Message} - 記錄訊息
  • {Exception} - 例外資訊
  • {NewLine} - 新行字元
  • {ThreadId} - 執行緒 ID
  • {EvtId} - 事件 ID
  • {EvtName} - 事件名稱

資料庫欄位對應

DbLogger 支援以下欄位:

  • Category - 記錄來源類別
  • EventId - 事件 ID
  • EventName - 事件名稱
  • Level - 記錄層級
  • Message - 記錄訊息
  • Scope - 記錄範圍
  • ThreadId - 執行緒 ID
  • Timestamp - 時間戳記

注意事項

  • 檔案記錄器會自動建立目錄
  • 資料庫記錄器需要預先建立資料表
  • 所有記錄器都會自動過濾 ANSI 顏色碼
  • 支援記錄範圍 (Scope) 功能
  • 執行緒安全設計

版本歷程

v1.22.395 (2025-08-11)

  • 修改 FileLoggerDbEventLogger 類別標記為 partial,並使用 GeneratedRegex 特性優化正則表達式的性能
Product 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.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.22.412 137 8/12/2025
1.22.395 124 8/11/2025
1.21.390 494 7/23/2025
1.20.385 175 3/17/2025
1.20.382 152 3/17/2025

### v1.22.395 (2025-08-11)
- 修改 `FileLogger` 和 `DbEventLogger` 類別標記為 partial,並使用 GeneratedRegex 特性優化正則表達式的性能