2012-02-11 93 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的招贴儿童之一)。将日志记录首选项卸载到发布版本可以忽略的配置设置。你会为自己节省很多头痛。