All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.nflow.engine.internal.util.PeriodicLogger Maven / Gradle / Ivy

There is a newer version: 10.0.0
Show newest version
package io.nflow.engine.internal.util;

import static org.joda.time.DateTimeUtils.currentTimeMillis;

import org.slf4j.Logger;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
 * PeriodicLogger logs once per given periodInSeconds period. Typically used in a loop where you don't want to log at every
 * iteration, but want to get a log row e.g. once per minute. Not thread safe.
 */
@SuppressFBWarnings(value = "LO_SUSPECT_LOG_PARAMETER", justification = "we are wrapping the logger here")
public class PeriodicLogger {
  private long previousLogging;
  private final int periodInSeconds;
  private final Logger logger;

  public PeriodicLogger(Logger logger, int periodInSeconds) {
    this.logger = logger;
    this.periodInSeconds = periodInSeconds;
  }

  public void info(String message, Object... parameters) {
    if (canLog()) {
      logger.info(message, parameters);
    }
  }

  public void warn(String message, Object... parameters) {
    if (canLog()) {
      logger.warn(message, parameters);
    }
  }

  private boolean canLog() {
    long currentPeriod = periodNumber();
    if (previousLogging != currentPeriod) {
      previousLogging = currentPeriod;
      return true;
    }
    return false;
  }

  private long periodNumber() {
    return currentTimeMillis() / 1000 / periodInSeconds;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy