Adding logs to code or logging requests-responses in any application has become an essential part of programming these days. Nearly every software application contains TBs of log files. Often programmers take logging for granted because of easy logging frameworks like slf4j, log4j. We hardly worry about the role of logs in our application performance.
Logging is indeed important but we need to keep in mind the extent of its usage. So lets discuss how much logging is healthy for a code. Here I have created a small code exercise to identify difference in the method execution time using methods containing log and a plain method execution.
I have used Google Caliper for micro benchmarking my methods and Log4J for adding logs to the code.
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import org.apache.log4j.Logger;
public class LoggingBenchMark extends SimpleBenchmark {
final static Logger logger = Logger.getLogger(LoggingBenchMark.class);
public static void main(String[] args) throws Exception {
new Runner().run(
LoggingBenchMark.class.getName()
);
}
private static final int SET_SIZE = 100000;
public void timeWithoutLog(int reps) throws InterruptedException {
for (int i = 0; i < reps; i++) {
for (int j = 0; j < SET_SIZE; j++) {
try {
performSomething(j);
} catch (Exception e) {
}
}
}
}
public void timeWithPlainLog(int reps) throws InterruptedException {
for (int i = 0; i < reps; i++) {
for (int j = 0; j < SET_SIZE; j++) {
try {
logger.info("testing logs adding here");
performSomething(j);
} catch (Exception e) {
}
}
}
}
public void timeWithLogExecively(int reps) {
for (int i = 0; i < reps; i++) {
for (int j = 0; j < 10000; j++) {
try {
logger.info("testing logs adding here");
performSomething(j);
} catch (Exception e) {
logger.error("exception in method : {}",e);
}
logger.debug("debug exception in method");
}
logger.info("some more logs");
}
}
public void performSomething(int number) {
if (number / 100 == 0) {
throw new RuntimeException();
}
}
}
Just copy and run this code on your local, you will see the difference in the method execution time with log and without log is more than 2500%. With method performance, excessive logging also affects CPU usage for file I/O and the server space too.
Logging application flows is necessary but overuse of logs to code flows has its drawbacks. Some ways of keeping logs to a minimum are by having a proper log level configured in application, avoiding the use of calculations/fetching data in the logging statements.
Leave a reply to Reynaldo91 Cancel reply