Log events in Java summarily, not per occurence

Viewed 122

My Java application does quite a lot of synchronization with databases. Each such single event is logged, e.g.

logger.info("Starting synchronization...");
synchronizeWithDatabase();  
logger.info("Synchronization has ended.");

This clutters logs quite a lot. Would it be possible to log a summary every hour (e.g. "there were 60 successful synchronization events from 12:00:00 to 13:00:00") and only log errors per occurrence? I'm using slf4j Logger

1 Answers

The straightforward way is to write code to do what you want. Write a wrapper class that, for each "event", tracks the last time you actually logged the event, and the number of times it has occurred.

Then on a call for which the time-since-logged exceeds an hour, actually write the log message, and reset the counter.


Here's a sketch off the top of my head. Hasn't been near a compiler. Not intended as a fully-baked solution.

class QuenchData {
    private static final long delta = 1000 * 60 * 60; // 1 hr
    private long lastLogTime;
    private int count;
    void log(String message, Logger logger) {
       long now = System.getTimeInMillis();
       if (now < lastLogTime || now-lastLogTime >= delta) {
            String andAlso = String.format(" [occurred %d times]", count);
            logger.log(message + andAlso);
            lastLogTime = now;
            count = 0;
       } else
            count++;
       }
    }
} 

class QuenchedLogger {
    private Logger logger = new Logger(...whatever...);
    private Map<String, QuenchData> history = new HashMap<>();
      :
    synchronized void log(String message) {
       QuenchData qd = history.get(message);
       if (qd == null)
           history.put(message, (qd = new QuenchData()));
       qd.log(message, logger);
    }
}

      
Related