gpt4 book ai didi

c# - 如何在发布版本中删除对 log4net 的依赖?

转载 作者:太空宇宙 更新时间:2023-11-03 19:25:12 24 4
gpt4 key购买 nike

在我的 C# 项目中,我使用 log4net 进行调试。但是对于发布版本,我需要删除对 log4net 的任何依赖。我不确定什么是正确的方法。

代码中有 #if DEBUG ... endif 非常困惑,当我在 Debug 或 Release 模式下编译时,我必须手动添加/删除对 log4net 的引用。

我考虑过的另一个选择是以某种方式在 Release 构建中用模拟类切换“真实的”lotg4net,但我不确定如何做到这一点。

在 Release 构建中删除依赖项(在我的例子中是 log4net)的最佳方法是什么?

最佳答案

按照 M.Babcock 的回答:您在依赖倒置之后。您不一定必须使用依赖注入(inject)容器,但您需要抽象您的日志记录。

像这样:

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/

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

空日志: 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

希望对您有所帮助。

关于c# - 如何在发布版本中删除对 log4net 的依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com