将代码中的 Appender 添加到 Root 以进行测试 - Log4Net

Adding an Appender in Code to Root for Tests - Log4Net

我正在尝试通过测试 class 中的代码向 root 记录器添加自定义附加程序。我在名为 Logging.cs.

的包装器 class 中配置了 log4net

这是我的构造函数 Logging.cs class:

public Logging(Type type)
{
    XmlDocument log4netConfig = new XmlDocument();
    log4netConfig.Load(File.OpenRead("log4net.config"));

    var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

    XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

    log4netLogger = LogManager.GetLogger(type);
    LogManager.GetLogger(type);
}

看了一些示例后,我将其编码到我未完成的测试方法中:

[Fact]
public void TestOutput()
{
    var appender = new StringAppender();

    var logger = new Logging(typeof(TestLibrary));

    Hierarchy h = (Hierarchy)log4net.LogManager.GetRepository();

    Logger rootLogger = h.Root;
}

但是,GetRepository() 需要一个回购名称作为 string,我不确定,一般来说我不知道​​我是否走在正确的道路上.

这是自定义附加程序:

public class StringAppender : AppenderSkeleton
{
    private string message { get; set; }
    protected override void Append(LoggingEvent loggingEvent)
    {
        message = loggingEvent.RenderedMessage;
    }

    public string GetMessage()
    {
        return message;
    }
}

经过更多的研究和实验,我发现如果你传入 Assembly.GetEntryAssembly()

LogManager.GetRepository() 对我有用

工作代码是:

// my custom appender
var appender = new StringAppender();

// my logger wrapper class
var logger = new Logging(typeof(TestLibrary));

// hierachy 
Hierarchy h = (Hierarchy)log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());

// get the root logger
Logger rootLogger = h.Root;

// add the appender
rootLogger.AddAppender(appender);

// set the root logger level
rootLogger.Level = Level.Debug;

// log4net via the wrapper class
logger.Debug("Hello, from TestLibrary Class");