ASP.NET 系列:單元測試之Log4Net

剛哥521發表於2016-02-03

使用Log元件時,我們通常自定義ILogger介面,使用Log4Net等元件進行適配來定義不同的實現類。使用Log4Net日誌元件時,為了即方便單元測試又能使用配置檔案,我們通過Log4Net的ILogger介面使用Log4Net,對Log4Net進行單元測試時我們可以通過使用MemoryAppender方式測試。

1.定義ILogger介面

ILogger可以通過使用日誌級別的列舉型別精簡方法數量,也可以不適用列舉直接定義多個方法。

public interface ILogger
{
    void Debug(string format, params string[] args);

    void Error(string format, params string[] args);

    void Fatal(string format, params string[] args);

    void Info(string format, params string[] args);

    void Warn(string format, params string[] args);
}

2.建立使用Log4Net適配的實現類Log4NetAdapter

public class Log4NetAdapter : ILogger
{
    private readonly ILog _rootLogger;

    public Log4NetAdapter(ILog rootLogger)
    {
        this._rootLogger = rootLogger;
    }

    public void Debug(string format, params string[] args)
    {
        if (this._rootLogger.IsDebugEnabled)
        {
            _rootLogger.Debug(string.Format(format, args));
        }
    }

    public void Info(string format, params string[] args)
    {
        if (this._rootLogger.IsInfoEnabled)
        {
            _rootLogger.Info(string.Format(format, args));
        }
    }

    public void Warn(string format, params string[] args)
    {
        if (this._rootLogger.IsWarnEnabled)
        {
            _rootLogger.Warn(string.Format(format, args));
        }
    }

    public void Error(string format, params string[] args)
    {
        if (this._rootLogger.IsErrorEnabled)
        {
            _rootLogger.Error(string.Format(format, args));
        }
    }

    public void Fatal(string format, params string[] args)
    {
        if (this._rootLogger.IsFatalEnabled)
        {
            _rootLogger.Fatal(string.Format(format, args));
        }
    }
}

3.使用MemoryAppender進行單元測試

public class Log4netAdapterTest
{
    private MemoryAppender _appender;

    [Fact]
    public void Test()
    {
        _appender = new MemoryAppender
        {
            Name = "Unit Testing Appender",
            Layout = new log4net.Layout.PatternLayout("%message")
        };
        _appender.ActivateOptions();

        var root = ((Hierarchy)log4net.LogManager.GetRepository()).Root;
        root.AddAppender(_appender);
        root.Repository.Configured = true;

        ILogger logger = new Log4NetAdapter(log4net.LogManager.GetLogger("root"));
        logger.Info("test {0}", "message");
        Assert.Equal(_appender.GetEvents()[0].MessageObject.ToString(), string.Format("test {0}", "message"));
    }
}

4.建立Log4NetLoggerFactory

通常我們使用配置檔案方式配置Log4Net,因此建立Log4NetLoggerFactory提供從配置檔案中建立的ILog物件。

public class LoggerFactory
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(LoggerFactory));

    static LoggerFactory()
    {
        log4net.Config.XmlConfigurator.Configure();
    }

    public static ILogger GetLogger()
    {
        return new Log4NetAdapter(log);
    }
}

參考的配置檔案

<configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>


<log4net>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="App_Data/Logs/log.txt" />
    <param name="AppendToFile" value="true" />
    <param name="RollingStyle" value="Date" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <preserveLogFileNameExtension value="true" />
    <datePattern value="yyyyMMdd" />
    <param name="StaticLogFileName" value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
    </layout>
  </appender>
</log4net>

執行結果:

4.通過依賴注入使用ILogger

在ASP.NET專案中使用時,通過DI容器進行注入。

protected void Application_Start()
{
    //...
    ObjectFactory.AddSingleton<ILogger, Log4NetAdapter>(LoggerFactory.GetLogger());
    //...
}

相關文章