log4j:防止重复日志消息的标准方法?

时间:2012-02-03 16:45:06

标签: java logging log4j

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

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

2 个答案:

答案 0 :(得分:3)

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

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

而不是:

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

这使得它最多记录1次5秒,并打印它应记录的次数(例如| 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;
        }
    }
}

答案 1 :(得分:2)

通过在每次记录错误时记录时间戳来控制它,然后只在某个时间段过去之后才记录它,这将非常简单。

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

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