Reputation: 9936
I am trying to find how I can log a debug message every few seconds to avoid log spamming.
Say, I have the below function.
public void doSomething() {
// log is a logger object from org.slf4j
log.debug("doSomething: Enter");
// do some task
log.debug("doSomething: Exit");
return;
}
This function gets called 100 times in a loop
for (int i = 0; i < 100; i++) {
doSomething();
thread.sleep(100); // sleep for 100 milli seconds
}
I do not want the log message to get printed 100 times. I want it to get printed every second or something like that.
Is there someway I can control this? I can think of passing the "iteration i" to doSomething() and printing the log only when I am on certain iteration.
Something like,
public void doSomething(int i) {
if (i == 25) {
// log is a logger object from org.slf4j
log.debug("doSomething: Enter");
}
// do some task
if (i == 25) {
// log is a logger object from org.slf4j
log.debug("doSomething: Exit");
}
return;
}
for (int i = 0; i < 100; i++) {
doSomething(i);
thread.sleep(100); // sleep for 100 milli seconds
}
Is there a better way to do this? Thanks!
Upvotes: 2
Views: 2661
Reputation: 2265
I am not sure what kind of logging framework you are using.If you happen to use log4j, I guess you can somehow configure the latency using a system property AsyncLogger.WaitStrategy. Have a look in https://logging.apache.org/log4j/log4j-2.3/manual/async.html.
Upvotes: 3
Reputation: 41625
When I had the same problem, I developed a throttled logger, which initially behaves like a normal logger. But after logging n
messages, all further messages are skipped until some time has passed. After each second, some more messages are allowed to be logged.
When starting to suppress messages, you should log about this, as well as when starting to log again.
Upvotes: 2