我可以让Log4J暂时抑制记录特定消息吗? [英] Can I make Log4J suppress logging specific messages for a time?

查看:101
本文介绍了我可以让Log4J暂时抑制记录特定消息吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个非常基本的要求,尽管很难有效实施:

I thought this is a pretty basic requirement, although difficult to implement efficiently:

在一个代码库中,我们记录了很多时间,具体取决于用户的行为.为了争辩,说每次单击按钮都会创建一条带有单击按钮名称的日志消息.

At one codebase, we log quite a bit, depending on user behavior. For the sake of argument say every click on a button creates a log message with the name of the clicked button.

现在,我不在乎每个单击的按钮.我很满足于每5分钟打印一次消息,而不考虑用户单击按钮的次数.

Now, I don't care about each and every clicked button. I'm quite content having one message printed once every 5 minutes, regardless of the number of times the user clicked the button.

我可以在用户代码中轻松完成此操作:

I can do this pretty easily in user code:

private static final Logger LOG = Logger.getLogger("buttons");
private static final long LOG_ONLY_EVERY = Duration.ofMinutes( 5 ).getSeconds();

private static final Map<String, Long> loggedViolations = new HashMap<>();

public static void logClick( String buttonName )
{
    String msg = "Button " + buttonName + " has been clicked";

    final long epochSecond = Instant.now( Clock.systemUTC() ).getEpochSecond();
    if ( !loggedViolations.containsKey( msg ) )
    {
        loggedViolations.put( msg, epochSecond );
    }
    if ( loggedViolations.get( msg ) + LOG_ONLY_EVERY < epochSecond )
    {
        LOG.warn( msg );
        loggedViolations.put( msg, epochSecond );
    }
}

我的问题是:SLF4J或Log4J可以为我这样做吗?怎么样?

My question is: can SLF4J or Log4J do this for me? How?

是的,我知道上面的代码缺少同步.如果上述问题的答案是不,请您自己做"-在多线程环境中,以上内容是否安全(因为无论如何我都不会删除消息)?

And yes, I'm aware the above code is lacking synchronization. If the answer to the above question is "no, do it yourself" - would the above be safe in a multi-threaded environment (since I don't remove messages, anyway)?

推荐答案

使用 BurstFilter 并将其安装在buttons记录器上:

Use the BurstFilter and install it on the buttons logger:

BurstFilter提供了一种机制,通过在达到最大限制后通过静默丢弃事件来控制LogEvent的处理速度.

The BurstFilter provides a mechanism to control the rate at which LogEvents are processed by silently discarding events after the maximum limit has been reached.

对于Logback,请使用 DuplicateMessageFilter .

For Logback use the DuplicateMessageFilter.

这篇关于我可以让Log4J暂时抑制记录特定消息吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆