設計靈活可擴充的日誌系統,核心採用適配器模式:定義 `ILogTarget` 介面,`FileLog`/`DbLog`/`CloudLog` 實作不同輸出目標,`SmartLog` 外觀類統一入口,業務程式碼零耦合具體實作。
public enum LogLevel { Trace = 1, Bug, Error }
public interface ILogTarget
{
void Write(LogLevel level, string message, Exception ex = null);
}
public class FileLog : ILogTarget
{
private readonly string _path;
private readonly object _lock = new object();
public FileLog(string path) => _path = path;
public void Write(LogLevel level, string message, Exception ex = null)
{
string log = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} [{level}] {message}" +
(ex != null ? $"\r\n{ex}" : "");
lock (_lock)
{
File.AppendAllText(_path, log + Environment.NewLine);
}
}
}
public class DbLog : ILogTarget
{
private readonly string _connStr;
public DbLog(string connStr) => _connStr = connStr;
public void Write(LogLevel level, string message, Exception ex = null)
{
const string sql = @"INSERT INTO SysLog (Level, Message, StackTrace, CreateTime)
VALUES (@Level, @Msg, @Stack, @Time)";
using (var conn = new SqlConnection(_connStr))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Level", level.ToString());
cmd.Parameters.AddWithValue("@Msg", message);
cmd.Parameters.AddWithValue("@Stack", ex?.ToString() ?? "");
cmd.Parameters.AddWithValue("@Time", DateTime.Now);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
public class SmartLog
{
private readonly ILogTarget _target;
public SmartLog(ILogTarget target) => _target = target;
public void Trace(string msg) => _target.Write(LogLevel.Trace, msg);
public void Bug(string msg, Exception ex = null) => _target.Write(LogLevel.Bug, msg, ex);
public void Error(string msg, Exception ex = null) => _target.Write(LogLevel.Error, msg, ex);
}
// 組態階段決定輸出目標 (可讀 web.config / DI 容器注入)
ILogTarget target = new FileLog(Server.MapPath("~/App_Data/Logs/app.log"));
// ILogTarget target = new DbLog(ConfigurationManager.ConnectionStrings["Logs"].ConnectionString);
// ILogTarget target = new CompositeLog(new FileLog(...), new DbLog(...)); // 多目標
var log = new SmartLog(target);
try { RiskyOperation(); }
catch (Exception ex) { log.Error("操作失敗", ex); }
// 同時寫入多個目標
public class CompositeLog : ILogTarget
{
private readonly IEnumerable _targets;
public CompositeLog(params ILogTarget[] targets) => _targets = targets;
public void Write(LogLevel level, string message, Exception ex = null)
{
foreach (var t in _targets) t.Write(level, message, ex);
}
}
// ASP.NET Core DI 註冊
services.AddSingleton(sp => new CompositeLog(
new FileLog("logs/app.log"),
new DbLog(sp.GetRequiredService().GetConnectionString("Logs"))
));
services.AddScoped();
LogContext 推送屬性。自寫日誌僅適合極簡專案或教學;正式專案請直接上 Serilog/NLog,省時且功能完備 (非同步寫入、滾動檔案、結構化查詢、告警整合)。