系統上線後,操作審計與錯誤診斷是維運的雙核心需求。本篇奠基日誌與例外處理機制:設計資料庫日誌表、建立 EF 實體模型、引入虛擬用戶上下文,為後續的日誌記錄、例外捕獲、全域錯誤處理鋪路。
在權限系統完成前,先建立臨時用戶模型供日誌記錄使用:
// App.Models/Sys/AccountModel.cs
namespace App.Models.Sys {
public class AccountModel {
public string Id { get; set; }
public string TrueName { get; set; }
}
}
在 HomeController 或 AccountController 初始化:
public ActionResult Index() {
// 模擬登入用戶(正式環境由驗證系統提供)
var account = new AccountModel { Id = "admin", TrueName = "系統管理員" };
Session["Account"] = account;
return View();
}
USE [YourDB]
GO
CREATE TABLE [dbo].[SysLog] (
[Id] [varchar](50) NOT NULL PRIMARY KEY, -- GUID 主鍵
[Operator] [varchar](50) NULL, -- 操作人帳號/姓名
[Message] [varchar](500) NULL, -- 操作詳情/例外堆疊
[Result] [varchar](20) NULL, -- 結果:Success/Fail/Exception
[Type] [varchar](20) NULL, -- 類型:Create/Edit/Delete/Query/Login/Error
[Module] [varchar](20) NULL, -- 業務模組:SysSample/SysUser/SysRole...
[CreateTime] [datetime] NULL -- 操作時間
) ON [PRIMARY]
GO
-- 索引優化常見查詢
CREATE INDEX IX_SysLog_CreateTime ON SysLog(CreateTime DESC);
CREATE INDEX IX_SysLog_Operator ON SysLog(Operator);
CREATE INDEX IX_SysLog_Module_Type ON SysLog(Module, Type);
// App.Models/Sys/SysLogModel.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace App.Models.Sys {
public class SysLogModel {
[Display(Name = "ID")]
public string Id { get; set; }
[Display(Name = "操作人")]
public string Operator { get; set; }
[Display(Name = "訊息")]
public string Message { get; set; }
[Display(Name = "結果")]
public string Result { get; set; }
[Display(Name = "類型")]
public string Type { get; set; }
[Display(Name = "模組")]
public string Module { get; set; }
[Display(Name = "建立時間")]
public DateTime? CreateTime { get; set; }
}
}
| 層級 | 記錄時機 | 記錄內容 | 範例 |
|---|---|---|---|
| Controller | Action 執行前/後 | 操作類型、參數、結果、耗時 | Create、Edit、Delete、Export |
| Service/BLL | 業務規則驗證失敗 | 違反規則詳情、相關實體 ID | 庫存不足、權限不足、狀態衝突 |
| Repository/DAL | 資料庫例外、Deadlock | SQL 指令、參數、堆疊追蹤 | Connection Timeout、PK Violation |
| Global.asax | 未處理例外、404、500 | 完整例外物件、請求 URL、用戶代理 | NullReference、SqlException |
// App.IBLL/Sys/ISysLogBLL.cs
namespace App.IBLL.Sys {
public interface ISysLogBLL {
int Create(SysLogModel entity);
IQueryable GetList(string operatorName, string module, string type, DateTime? startTime, DateTime? endTime, int page, int rows);
int GetTotalCount(string operatorName, string module, string type, DateTime? startTime, DateTime? endTime);
// 可選:統計分析方法
Dictionary GetModuleOperationStats(DateTime start, DateTime end);
Dictionary GetErrorTrend(int days);
}
}
接下來三講將完整實作:
ResultHelper、日誌處理器 LogHandler、Controller 整合實戰Application_Error 全域例外處理、自訂錯誤頁面、web.config 配置扎實的日誌基礎設施是系統可觀測性的基石,投入前期設計成本,將在後期維運中獲得百倍回報。