這篇文章主要介紹了.NET 日誌系統設計思路及實現代碼,有需要的朋友可以參考一下
日誌很明顯是協助大家定位到問題的一個很重要的手段,本來是想直接使用的NLog 來做系統的日誌工具,哎傷不起,一變態非要說這個有很多不可控制的因素,這裡我給大家講一下我是怎麼實現日誌模組的,歡迎拍磚 總體架構圖 • 在這裡我把日子的等級分為 跟蹤,BUG 和錯誤 3種 定義枚舉如下 代碼如下:/// <summary> /// 日誌等級 /// </summary> public enum Loglevel { Track=1, Bug, Error } • 這裡考慮日誌的模組的可擴充性 (這裡支援 資料庫 和檔案 2種方式) 這裡使用適配器模式來完成本模組。 這裡給大家來年終福利。貼點代碼定義一個介面ILogTarget代碼如下:public interface ILogTarget { /// <summary> /// 寫入追蹤資訊 /// </summary> /// <param name="LogContent"></param> void WriteTrack(string LogContent); /// <summary> /// 寫入BUG資訊 /// </summary> /// <param name="LogContent"></param> void WriteBug(string LogContent); /// <summary> /// 寫入錯誤資訊 /// </summary> /// <param name="LogContent"></param> void WriteError(string LogContent); } • FileLog ,和DBLog 2個類實現上面的介面 這裡不貼上具體的現實 代碼如下:/// <summary> /// 檔案日誌實作類別 /// </summary> public class FileLog : ILogTarget { public void WriteTrack(string LogContent) { throw new NotImplementedException(); } public void WriteBug(string LogContent) { throw new NotImplementedException(); } public void WriteError(string LogContent) { throw new NotImplementedException(); } } 代碼如下:public class DBLog : ILogTarget { public void WriteTrack(string LogContent) { throw new NotImplementedException(); } public void WriteBug(string LogContent) { throw new NotImplementedException(); } public void WriteError(string LogContent) { throw new NotImplementedException(); } } 代碼如下:public class SmartLog { private ILogTarget _adaptee; public SmartLog(ILogTarget tragent) { this._adaptee = tragent; } public void WriteTrack(string LogContent) { _adaptee.WriteTrack(LogContent); } public void WriteBug(string LogContent) { _adaptee.WriteBug(LogContent); } public void WriteError(string LogContent) { _adaptee.WriteError(LogContent); } } • 調用方式代碼如下:SmartLog log =new SmartLog (new FileLog()); log.WriteTrack("Hello word");