2012-02-11 50 views
0

在我的C#項目中,我使用log4net進行調試。但是對於Release版本,我需要刪除對log4net的任何依賴。我不確定什麼是正確的方式去做。如何在Release版本中刪除對log4net的依賴關係?

#if DEBUG ... endif通過代碼非常混亂,當我在Debug或Release模式下編譯時,我必須手動添加/刪除引用到log4net。

我想過的另一個選擇是以某種方式在Release版本中用模擬類切換「真正的」lotg4net,但我不知道如何做到這一點。

在Release版本中,刪除依賴項log4net的最佳方法是什麼?

+0

嘲笑是測試。其生產版本傾向於與控制反轉或依賴注入一致。 – 2012-02-11 05:38:15

回答

3

沿着M.Babcock的答案:你是在依賴倒置之後。你不一定使用依賴注入容器,但你需要抽象你的日誌。

事情是這樣的:

public interface ILog 
{ 
    void Trace(string message); 
    void Debug(string message); 
    void Error(string message); 
    // and whatever you need 
} 

然後你有不同的實現:

public class NullLog : ILog { ... } // does nothing --- all calls are empty 
public class Log4NetLog : ILog { ... } // initializes Log4Net and does logging 

然後,您可以使用靜態類作爲主要切入點:

public static class Log 
{ 
    private ILog log = new NullLogger(); 

    public static void Assign(ILog log) 
    { 
     this.log = log; 
    } 

    public static void Debug(string message) 
    { 
     log.Debug(message); 
    } 

    // ...and other implementations... 
} 

現在你需要在啓動代碼中連接它。在這裏,您可以使用容器或使用條件編譯:

#if DEBUG 
    Log.Assign(new Log4NetLogger); 
#endif 

這些是廣泛的筆畫。我有一些日誌記錄基礎代碼作爲我的服務總線的一部分:http://shuttle.codeplex.com/

的ILog: http://shuttle.codeplex.com/SourceControl/changeset/view/c49f328edd17#Shuttle.Core%2fsource%2fShuttle.Core.Infrastructure%2fLogging%2fILog.cs

NullLog: http://shuttle.codeplex.com/SourceControl/changeset/view/c49f328edd17#Shuttle.Core%2fsource%2fShuttle.Core.Infrastructure%2fLogging%2fNullLog.cs

Log4NetLog: http://shuttle.codeplex.com/SourceControl/changeset/view/c49f328edd17#Shuttle.Core%2fsource%2fShuttle.Core.Infrastructure.Log4Net%2fLog4NetLog.cs

希望有所幫助。

3

依賴注入是最好的選擇。通過在兩者之間添加DI容器,將日誌庫從您的物理實現中抽象出來(日誌記錄是DI/IoC和AOP的招貼兒童之一)。將日誌記錄首選項卸載到發佈版本可以忽略的配置設置。你會爲自己節省很多頭痛。