【问题标题】:log4j: Standard way to prevent repetitive log messages?log4j:防止重复日志消息的标准方法?
【发布时间】:2012-02-03 16:45:06
【问题描述】:

我们的生产应用程序在无法建立 TCP/IP 连接时记录错误。由于它不断地重试连接,它一遍又一遍地记录相同的错误消息。同样,如果某些实时资源在一段时间内不可用,应用程序中的其他运行组件可能会进入错误循环。

是否有任何标准方法来控制记录相同错误的次数? (我们使用的是 log4j,所以如果 log4j 有任何扩展来处理这个问题,那就完美了。)

【问题讨论】:

标签: java logging log4j


【解决方案1】:

我刚刚创建了一个使用 log4j 解决这个确切问题的 Java 类。当我想记录一条消息时,我只是做这样的事情:

LogConsolidated.log(logger, Level.WARN, 5000, "File: " + f + " not found.", e);

代替:

logger.warn("File: " + f + " not found.", e);

这使得它每 5 秒最多记录 1 次,并打印它应该记录的次数(例如 |x53|)。显然,您可以做到这一点,这样您就没有那么多参数,或者通过执行 log.warn 或其他操作来拉出级别,但这适用于我的用例。

import java.util.HashMap;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class LogConsolidated {

    private static HashMap<String, TimeAndCount> lastLoggedTime = new HashMap<>();

    /**
     * Logs given <code>message</code> to given <code>logger</code> as long as:
     * <ul>
     * <li>A message (from same class and line number) has not already been logged within the past <code>timeBetweenLogs</code>.</li>
     * <li>The given <code>level</code> is active for given <code>logger</code>.</li>
     * </ul>
     * Note: If messages are skipped, they are counted. When <code>timeBetweenLogs</code> has passed, and a repeat message is logged, 
     * the count will be displayed.
     * @param logger Where to log.
     * @param level Level to log.
     * @param timeBetweenLogs Milliseconds to wait between similar log messages.
     * @param message The actual message to log.
     * @param t Can be null. Will log stack trace if not null.
     */
    public static void log(Logger logger, Level level, long timeBetweenLogs, String message, Throwable t) {
        if (logger.isEnabledFor(level)) {
            String uniqueIdentifier = getFileAndLine();
            TimeAndCount lastTimeAndCount = lastLoggedTime.get(uniqueIdentifier);
            if (lastTimeAndCount != null) {
                synchronized (lastTimeAndCount) {
                    long now = System.currentTimeMillis();
                    if (now - lastTimeAndCount.time < timeBetweenLogs) {
                        lastTimeAndCount.count++;
                        return;
                    } else {
                        log(logger, level, "|x" + lastTimeAndCount.count + "| " + message, t);
                    }
                }
            } else {
                log(logger, level, message, t);
            }
            lastLoggedTime.put(uniqueIdentifier, new TimeAndCount());
        }
    }

    private static String getFileAndLine() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        boolean enteredLogConsolidated = false;
        for (StackTraceElement ste : stackTrace) {
            if (ste.getClassName().equals(LogConsolidated.class.getName())) {
                enteredLogConsolidated = true;
            } else if (enteredLogConsolidated) {
                // We have now file/line before entering LogConsolidated.
                return ste.getFileName() + ":" + ste.getLineNumber();
            }
        }
        return "?";
    }       

    private static void log(Logger logger, Level level, String message, Throwable t) {
        if (t == null) {
            logger.log(level, message);
        } else {
            logger.log(level, message, t);
        }
    }

    private static class TimeAndCount {
        long time;
        int count;
        TimeAndCount() {
            this.time = System.currentTimeMillis();
            this.count = 0;
        }
    }
}

【讨论】:

  • 请注意,地图访问不是线程安全的。此外,执行实际日志记录的 else 情况可能会导致两个线程同时记录相同的错误。
  • 没错,从完全相同的代码行调用记录器的两个线程可能会导致记录器两次记录相同的内容。我可以通过使对映射线程的访问安全来解决这个问题,但我会放弃性能损失,以免出现重复的日志消息。整个事情的主要思想是在应用程序进入不良状态时切断垃圾邮件消息,以便更容易消化日志。感谢您指出问题,我真的很感激!
  • 错误警报:lastTimeAndCount.time 应在每条日志消息之后重置,否则在 time+delta 之后 - 您最终会记录所有消息。
  • 看起来唯一标识符总是从堆栈跟踪中提取,如果记录的只是信息怎么办
【解决方案2】:

通过在每次记录错误时记录时间戳来控制这一点相当简单,然后仅在经过一段时间后才记录下一次。

理想情况下,这将是 log4j 中的一个功能,但在您的应用程序中对其进行编码并不算太糟糕,您可以将其封装在帮助程序类中以避免整个代码中的样板。

显然,每个重复的日志语句都需要某种唯一 ID,以便您可以合并来自同一来源的语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多