简体   繁体   English

如何使log4net.dll可选?

[英]How do I make log4net.dll optional?

I use log4net to implement logging in my .NET app. 我使用log4net在我的.NET应用程序中实现日志记录。 However I do not want to distribute the 300kb log4net.dll for every user but instead send this dll to the user if he has problems and I want him to provide logs. 但是,我不想为每个用户分发300kb log4net.dll,而是如果他有问题并且我希望他提供日志,则将此dll发送给用户。

So, is it possible to make my app run whether or not the dll is there? 那么,是否有可能让我的应用程序运行是否存在dll? Of course for logging the dll would be needed, but if no logging is needed, the app should run without the dll. 当然,对于日志记录,将需要dll,但如果不需要日志记录,应用程序应该在没有dll的情况下运行。

Yes, it is possible. 对的,这是可能的。

First create an interfase with all your log methods: 首先使用所有日志方法创建一个interfase:

public interface ILogger
{
    void Write(string message);
    // And much more methods.
}

Now create two instances, a dummy instance (lets call it DummyLogger ), and a instance which will send its messages to Log4Net ( Log4NetLogger ). 现在创建两个实例,一个虚拟实例(让我们称之为DummyLogger ),以及一个将其消息发送到Log4Net( Log4NetLogger )的实例。

To finish, create a factory class: 要完成,请创建一个工厂类:

static public class LogFactory
{
     static public ILogger CreateLogger()
     {
          if (/*Check if Log4Net is available*/)
               return new Log4NetLogger();
          else
               return new DummyLogger();
     }
}

You could check if Log4Net is available by simply checking if the file is in your bin-folder. 您可以通过检查文件是否在bin-folder中来检查Log4Net是否可用。 Something like: 就像是:

File.Exists(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.dll")

But I can imagine that you want to do other checks, like if it exists in the GAC or whatever. 但我可以想象你想要做其他检查,比如它是否存在于GAC或其他任何方面。

Now you can use your factory to create your logger and "write" messages to the log: 现在,您可以使用工厂创建记录器并将“写入”消息写入日志:

ILogger logger = LoggerFactory.CreateLogger();
logger.Write("I am logging something!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM