以编程方式在 log4net 中添加和删除日志附加程序

发布于 2024-08-06 22:23:19 字数 177 浏览 3 评论 0原文

我有一个使用 log4net 的组件。我想创建单元测试,以验证某些错误条件是否会导致正确的日志记录。

我认为最好的方法是创建一个 ILogAppender 实现,例如一个模拟。然后,我会在测试设置期间将日志附加程序添加到 log4net,检查测试验证期间写入的内容,并在测试拆卸期间再次将其删除。

这可能吗?

I have a component that uses log4net. I want to create unit tests, that validate that certain error conditions result in the correct logging.

I was thinking that the best way to do this is to create an ILogAppender implementation, for example a mock. I would then add the log appender to log4net during test setup, inspect what was written during test validation, and remove it again during test teardown.

Is this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我乃一代侩神 2024-08-13 22:23:19

使用 BasicConfigurator 适合单元测试(OP 要求的内容,但不是主题行中的内容)。其他答案抓取特定记录器的输出。

我想要它全部(这是网站内的“自测试”页面)。最后我基本上做了以下事情:

var root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root;
var attachable = root as IAppenderAttachable;

var appender = new log4net.Appender.MemoryAppender();
if(attachable!=null)
    attachable.AddAppender(appender);
// do stuff
var loggingEvents = appender.GetEvents();
foreach (var loggingEvent in loggingEvents)
    loggingEvent.WriteRenderedMessage(writer);
if(attachable!=null)
    attachable.RemoveAppender(appender);

...但是按照@Pawel的方法包装为一次性的

更新:Pawel的答案已被删除,所以我在这里添加他的链接:
以编程方式检查 Log4Net 日志

Using the BasicConfigurator is fine for unit testing (what the OP asked for, but not what's in the subject line). The other answers grab output for a specific logger.

I wanted it all (this was a 'self test' page within a website). In the end I did basically the following:

var root = ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root;
var attachable = root as IAppenderAttachable;

var appender = new log4net.Appender.MemoryAppender();
if(attachable!=null)
    attachable.AddAppender(appender);
// do stuff
var loggingEvents = appender.GetEvents();
foreach (var loggingEvent in loggingEvents)
    loggingEvent.WriteRenderedMessage(writer);
if(attachable!=null)
    attachable.RemoveAppender(appender);

...but wrapped up as a Disposable as per @Pawel's approach

UPDATE: Pawel's answer was deleted, so I am adding his link here:
Programmatically check Log4Net log.

甜点 2024-08-13 22:23:19

我一直在使用 BasicConfigurator 配置了 MemoryAppender。此附加程序可让您获取测试期间记录的内存中消息。

I have been using the BasicConfigurator configured with a MemoryAppender. This appender lets you get to the in-memory messages logged during your test.

断念 2024-08-13 22:23:19

以下代码最初是在 apache 邮件列表档案 并且应该解决在代码中添加和删除 log4net 附加程序的问题

/// <summary>
/// dataLog
/// </summary>
protected static readonly IDeviceCommunicationsLog dataLog =
DeviceCommunicationsLogManager.GetLogger("LIS3.Data");


Each connection adds and removes a file appender programmatically:

/// <summary>
/// add connection specific appender
/// </summary>
void AddAppender()
{
    // check if logging is endabled
    if( this.IsLoggingEnabled() )
    {
        try
        {
            // get the interface
            IAppenderAttachable connectionAppender = (IAppenderAttachable)this.DataLog.Logger;
            // need some application configuration settings
            NameValueCollection appSettings = ConfigurationSettings.AppSettings;
            // get the layout string
            string log4netLayoutString = appSettings["log4net.LIS3.LayoutString"];
            if( log4netLayoutString == null )
            {
                // use default setting
                log4netLayoutString = "%d [%x]%n   %m%n  %P MessageData}%n%n";
            }
            // get logging path
            string log4netPath = appSettings["log4net.Path"];
            if( log4netPath == null )
            {
                // use default path
                log4netPath = ".\\";
            }
            // create the appender
            this.rollingFileAppender = new RollingFileAppender();
            // setup the appender
            this.rollingFileAppender.MaxFileSize = 10000000;
            this.rollingFileAppender.MaxSizeRollBackups = 2;
            this.rollingFileAppender.RollingStyle =   RollingFileAppender.RollingMode.Size;
            this.rollingFileAppender.StaticLogFileName = true;
            string appenderPath = LogSourceName + ".log";
            // log source name may have a colon - if soreplace with underscore
            appenderPath = appenderPath.Replace( ':', '_' );
            // now add to log4net path
            appenderPath = Path.Combine( log4netPath, appenderPath );
            // update file property of appender
            this.rollingFileAppender.File = appenderPath;
            // add the layout
            PatternLayout patternLayout = new PatternLayout(   log4netLayoutString );
            this.rollingFileAppender.Layout = patternLayout;
            // add the filter for the log source
            NDCFilter sourceFilter = new NDCFilter();
            sourceFilter.StringToMatch = this.LogSourceName;
            this.rollingFileAppender.AddFilter( sourceFilter);
            // now add the deny all filter to end of the chain
            DenyAllFilter denyAllFilter = new DenyAllFilter();
            this.rollingFileAppender.AddFilter( denyAllFilter );
            // activate the options
            this.rollingFileAppender.ActivateOptions();
            // add the appender
            connectionAppender.AddAppender( this.rollingFileAppender );
        }
        catch( Exception x )
        {
            this.ErrorLog.Error( "Error creating LIS3 data log appender for " + LogSourceName, x );
        }
    }
}
/// <summary>
/// remove connection specific appender
/// </summary>
void RemoveAppender()
{
    // check if we have one
    if( this.rollingFileAppender != null )
    {
        // cast to required interface
        IAppenderAttachable connectionAppender = (IAppenderAttachable)this.DataLog.Logger;
        // remove the appendier
        connectionAppender.RemoveAppender( rollingFileAppender );
        // set to null
        this.rollingFileAppender = null;
    }
}

The following code was originally found on the apache mailing list archives and should solve the problem of adding and removing log4net appenders in code

/// <summary>
/// dataLog
/// </summary>
protected static readonly IDeviceCommunicationsLog dataLog =
DeviceCommunicationsLogManager.GetLogger("LIS3.Data");


Each connection adds and removes a file appender programmatically:

/// <summary>
/// add connection specific appender
/// </summary>
void AddAppender()
{
    // check if logging is endabled
    if( this.IsLoggingEnabled() )
    {
        try
        {
            // get the interface
            IAppenderAttachable connectionAppender = (IAppenderAttachable)this.DataLog.Logger;
            // need some application configuration settings
            NameValueCollection appSettings = ConfigurationSettings.AppSettings;
            // get the layout string
            string log4netLayoutString = appSettings["log4net.LIS3.LayoutString"];
            if( log4netLayoutString == null )
            {
                // use default setting
                log4netLayoutString = "%d [%x]%n   %m%n  %P MessageData}%n%n";
            }
            // get logging path
            string log4netPath = appSettings["log4net.Path"];
            if( log4netPath == null )
            {
                // use default path
                log4netPath = ".\\";
            }
            // create the appender
            this.rollingFileAppender = new RollingFileAppender();
            // setup the appender
            this.rollingFileAppender.MaxFileSize = 10000000;
            this.rollingFileAppender.MaxSizeRollBackups = 2;
            this.rollingFileAppender.RollingStyle =   RollingFileAppender.RollingMode.Size;
            this.rollingFileAppender.StaticLogFileName = true;
            string appenderPath = LogSourceName + ".log";
            // log source name may have a colon - if soreplace with underscore
            appenderPath = appenderPath.Replace( ':', '_' );
            // now add to log4net path
            appenderPath = Path.Combine( log4netPath, appenderPath );
            // update file property of appender
            this.rollingFileAppender.File = appenderPath;
            // add the layout
            PatternLayout patternLayout = new PatternLayout(   log4netLayoutString );
            this.rollingFileAppender.Layout = patternLayout;
            // add the filter for the log source
            NDCFilter sourceFilter = new NDCFilter();
            sourceFilter.StringToMatch = this.LogSourceName;
            this.rollingFileAppender.AddFilter( sourceFilter);
            // now add the deny all filter to end of the chain
            DenyAllFilter denyAllFilter = new DenyAllFilter();
            this.rollingFileAppender.AddFilter( denyAllFilter );
            // activate the options
            this.rollingFileAppender.ActivateOptions();
            // add the appender
            connectionAppender.AddAppender( this.rollingFileAppender );
        }
        catch( Exception x )
        {
            this.ErrorLog.Error( "Error creating LIS3 data log appender for " + LogSourceName, x );
        }
    }
}
/// <summary>
/// remove connection specific appender
/// </summary>
void RemoveAppender()
{
    // check if we have one
    if( this.rollingFileAppender != null )
    {
        // cast to required interface
        IAppenderAttachable connectionAppender = (IAppenderAttachable)this.DataLog.Logger;
        // remove the appendier
        connectionAppender.RemoveAppender( rollingFileAppender );
        // set to null
        this.rollingFileAppender = null;
    }
}
请持续率性 2024-08-13 22:23:19

怎么样:

((log4net.Repository.Hierarchy.Logger) theLogger.Logger).RemoveAppender("SomeAppender");

添加相同。

How about:

((log4net.Repository.Hierarchy.Logger) theLogger.Logger).RemoveAppender("SomeAppender");

same for add.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文