萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

.NET 日誌系統設計:適配器模式支援多目標 (檔案/資料庫/雲端)

設計靈活可擴充的日誌系統,核心採用適配器模式:定義 `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();
        }
    }
}

外觀類:SmartLog


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();

生產級建議:直接採用成熟框架

  • Serilog:結構化日誌、豐富 Sink (檔案、DB、Seq、Elasticsearch、Azure)、LogContext 推送屬性。
  • NLog:高效能、XML/程式碼設定、支援 Layout/Target 組合。
  • Microsoft.Extensions.Logging:官方抽象,配合 Serilog/NLog Provider 使用。

自寫日誌僅適合極簡專案或教學;正式專案請直接上 Serilog/NLog,省時且功能完備 (非同步寫入、滾動檔案、結構化查詢、告警整合)。

copyright © 萬盛學電腦網 all rights reserved