ErrorLogCore 1.1.0

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package ErrorLogCore --version 1.1.0
                    
NuGet\Install-Package ErrorLogCore -Version 1.1.0
                    
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="ErrorLogCore" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ErrorLogCore" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="ErrorLogCore" />
                    
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 ErrorLogCore --version 1.1.0
                    
#r "nuget: ErrorLogCore, 1.1.0"
                    
#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 ErrorLogCore@1.1.0
                    
#: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=ErrorLogCore&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=ErrorLogCore&version=1.1.0
                    
Install as a Cake Tool

ErrorLogCore

輕量級 ASP.NET Core 錯誤記錄庫,搭配 NLog 整合與內嵌 Web UI,靈感來自 ELMAH。

功能特色

  • 自動捕捉未處理例外 — Middleware 自動攔截、記錄完整錯誤上下文
  • ILogger 整合 — 使用 ILogger<T> 手動記錄 log,自動寫入 ErrorLog UI
  • 內嵌 Web UI — 無需額外部署頁面檔案,NuGet 安裝即用
  • NLog 整合 — 自訂 Target 透過 NLog 管線寫入儲存後端
  • 多重儲存後端 — Memory(開發/測試)、Oracle(生產環境),可自行擴充
  • 自動資料清理 — 設定保留天數,背景服務定期刪除過期錯誤記錄
  • 完整請求上下文 — Form Data、Query String、Cookies、Headers、Request Body(JSON/XML)
  • 授權控制 — 支援角色、匿名存取、自訂授權政策、Basic Auth
  • AOT 相容 — 支援 Native AOT 編譯

系統需求

  • .NET 6.0+(支援 .NET 6、8、10)
  • ASP.NET Core 應用程式
  • NLog 6.x

快速開始

1. 安裝 NuGet 套件

方式 A:NuGet Registry(推薦)

dotnet add package ErrorLogCore

方式 B:本機 nupkg 檔案

dotnet add package ErrorLogCore --version 1.0.6 --source ./path/to/nupkg/folder

方式 C:本機資料夾作為 NuGet 來源(多專案共用)

# 一次性設定本機來源
dotnet nuget add source "C:\nuget-local" --name Local

# 將 nupkg 複製到該資料夾後,即可正常安裝
dotnet add package ErrorLogCore

2. 註冊服務

// Program.cs
using ErrorLogCore;
using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation;
using Microsoft.Extensions.FileProviders;
using NLog;

var builder = WebApplication.CreateBuilder(args);

// 啟用 Razor Pages Runtime Compilation 以支援內嵌 UI
builder.Services.AddRazorPages().AddRazorRuntimeCompilation(options =>
{
    var embeddedProvider = new EmbeddedFileProvider(
        typeof(ErrorLogCore.UI.ErrorLogEmbeddedUI).Assembly,
        "ErrorLogCore.UI.Pages"
    );
    options.FileProviders.Add(embeddedProvider);
});

// 註冊 ErrorLogCore
builder.Services.AddErrorLog(
    opt =>
    {
        opt.Path = "/errorlog";           // UI 存取路徑
        opt.AllowAnonymous = true;         // 開發環境允許匿名
        opt.ApplicationName = "MyApp";     // 顯示名稱
        opt.PageSize = 50;                 // 每頁筆數
    },
    storage => storage.UseMemory());       // 儲存後端

var app = builder.Build();

// 初始化 ServiceResolver(NLog Target 需要透過 DI 取得服務)
app.Services.GetRequiredService<ErrorLogCore.Configuration.ServiceProviderAccessor>();

// 設定 NLog(必須在 DI 容器建置之後)
LogManager.Setup()
    .SetupExtensions(ext => ext.RegisterTarget<ErrorLogCore.NLog.ErrorLogTarget>())
    .LoadConfigurationFromFile("nlog.config");

// 啟用 ErrorLogCore(內含路徑重寫 + 例外捕捉 middleware)
app.UseErrorLog();
app.UseRouting();
app.MapRazorPages();

app.Run();

3. 設定 NLog


<?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="ErrorLog" name="errorlog" />
  </targets>

  <rules>
    <logger name="ErrorLogCore" minlevel="Error" writeTo="errorlog" />
  </rules>
</nlog>

4. 瀏覽錯誤頁面

啟動應用程式後,前往 https://localhost:<port>/errorlog 即可查看錯誤紀錄。

組態設定

builder.Services.AddErrorLog(
    opt =>
    {
        opt.Path = "/errorlog";              // UI 路徑(預設 "/errorlog")
        opt.ApplicationName = "MyApp";       // 顯示名稱(預設自動取得組件名稱)
        opt.PageSize = 50;                   // 每頁筆數(預設 50)
        opt.AllowAnonymous = true;           // 允許匿名存取(預設 false)
        opt.AllowedRoles = ["Admin"];        // 允許存取的角色(預設 ["Admin"])
        opt.CaptureRequestBody = true;       // 捕捉 Request Body(預設 true)
        opt.MaxRequestBodySizeToCapture = 65536; // Body 最大捕捉量(預設 64KB)
        opt.MinimumLevel = LogLevel.Warning; // ILogger 最低記錄等級(預設 Warning)

        // Basic Auth 保護(設定後啟用)
        opt.BasicAuthUsername = "admin";    // Basic Auth 使用者名稱
        opt.BasicAuthPassword = "p@ssw0rd"; // Basic Auth 密碼

        // 自訂授權(設定後覆蓋 AllowedRoles)
        opt.AuthorizationPolicy = ctx =>
            ctx.Connection.RemoteIpAddress?.ToString() == "127.0.0.1";
    },
    storage => storage.UseMemory(maxCapacity: 500));

資料保留(自動清理)

設定 RetentionDays 後,背景服務會每 24 小時自動刪除超過保留天數的錯誤記錄。預設不啟用。

storage => storage.UseOracle(o =>
{
    o.ConnectionString = "...";
    o.RetentionDays = 30;  // 保留 30 天,超過的自動刪除
})
  • 設為 null(預設):不啟用自動清理
  • 設為 0 或負數:啟動時拋出 ArgumentOutOfRangeException
  • 僅支援 Oracle 儲存後端

儲存後端

Memory(開發/測試)

storage => storage.UseMemory()          // 預設容量 1000
storage => storage.UseMemory(500)       // 自訂容量

Oracle(生產環境)

storage => storage.UseOracle(o =>
{
    o.ConnectionString = "Data Source=mydb;User Id=myuser;Password=mypwd;";
    o.TableName = "ERROR_LOG";          // 預設 "ERROR_LOG"
    o.AutoCreateTable = true;           // 自動建表(預設 true)
    o.RetentionDays = 30;               // 保留天數(預設 null,不啟用)
})

自訂儲存

實作 IErrorLog 介面即可:

public class SqlServerErrorLog : IErrorLog
{
    public Task<string> LogAsync(ErrorLogEntry entry, CancellationToken ct = default) { ... }
    public Task<ErrorLogEntry?> GetAsync(string id, CancellationToken ct = default) { ... }
    public Task<int> GetCountAsync(CancellationToken ct = default) { ... }
    public Task<IReadOnlyList<ErrorLogEntry>> GetListAsync(int pageIndex, int pageSize, CancellationToken ct = default) { ... }
    public Task DeleteAsync(string id, CancellationToken ct = default) { ... }
    public Task DeleteAllAsync(CancellationToken ct = default) { ... }
}

錯誤紀錄欄位

每筆 ErrorLogEntry 包含以下資訊:

欄位 說明
Message 例外訊息
TypeName 例外類型完整名稱
StackTrace 堆疊追蹤
Detail 完整例外資訊
Url 請求 URL
HttpMethod HTTP 方法
User 已驗證的使用者名稱
StatusCode HTTP 狀態碼
Form 表單資料(FromForm)
QueryString 查詢字串參數
Cookies Request Cookies
Headers Request Headers
RequestBody Request Body(FromBody — JSON/XML)
ServerVariables 伺服器環境資訊

ILogger 整合

除了 Middleware 自動捕捉未處理例外外,也可透過 ILogger<T> 手動記錄 log。ILoggerProvider 會在 AddErrorLog() 時自動註冊,無需額外設定。

基本用法

public class MyService
{
    private readonly ILogger<MyService> _logger;

    public MyService(ILogger<MyService> logger) => _logger = logger;

    public void DoWork()
    {
        _logger.LogWarning("Something suspicious happened");

        try { /* ... */ }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to process request");
        }
    }
}

欄位對應

ILogger 呼叫方式 TypeName Message Detail
LogError(ex, "msg") 例外類型(如 System.InvalidOperationException "msg" 格式化訊息 + 完整例外資訊
LogWarning("msg") "Warning" "msg" "msg"
LogError("msg") "Error" "msg" "msg"

設定最低記錄等級

預設只記錄 Warning 及以上等級。可透過 MinimumLevel 調整:

opt.MinimumLevel = LogLevel.Error;  // 僅記錄 Error 和 Critical
opt.MinimumLevel = LogLevel.Information;  // 記錄 Information 及以上

注意: ILoggerProvider 僅在設定儲存後端(如 UseMemory()UseOracle())時才會註冊。未設定儲存後端時不會啟用。

Middleware 順序注意事項

UseErrorLog() 內部自動處理 middleware 順序,路徑重寫會在 UseRouting() 之前執行:

app.UseErrorLog();   // ← 包含路徑重寫 + 例外捕捉
app.UseRouting();
app.MapRazorPages();

如需精確控制,可分開呼叫:

app.UseEmbeddedUI(options);               // 路徑重寫(必須在 UseRouting 之前)
app.UseRouting();
app.UseMiddleware<ErrorLogMiddleware>(options);  // 例外捕捉
app.MapRazorPages();

授權

設定方式 說明
AllowAnonymous = true 允許所有存取(開發用)
BasicAuthUsername + BasicAuthPassword Basic Auth 保護(帳密都設定後啟用)
AllowedRoles = ["Admin"] 僅限指定角色(預設)
AuthorizationPolicy = ctx => ... 自訂授權邏輯

授權優先順序:AllowAnonymous > Basic Auth > AuthorizationPolicy > AllowedRoles > 拒絕

Basic Auth 範例

builder.Services.AddErrorLog(
    opt =>
    {
        opt.Path = "/errorlog";
        opt.BasicAuthUsername = "admin";
        opt.BasicAuthPassword = "p@ssw0rd";
    },
    storage => storage.UseMemory());

存取 /errorlog 時瀏覽器會彈出帳密對話框。未通過驗證回傳 HTTP 401。

授權

MIT License

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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 is compatible.  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