Java: Optimize Logging for Better Performance
By admin on Jan 15, 2009 in Java, Programming
Logging is necessary for troubleshooting purpose but excessive logging impacts performance. In most application, if you need high performance, you have to reduce the amount of logging.
If logging cannot be avoided, then you should try to output as much information as possible during a single logging operation, instead of logging multiple times consecutively.
E.g., avoid this pattern
logger.info("logging information") ;
logger.info("logging information again");
Join them in 1 single line instead
logger.info("logging information. " + "logging information again");
Also try to avoid logging inside a loop. If possible, log after you exit from the loop.
E.g.
// Lookup table
Map<String, String> lookup = new HashMap<String, String>(1);
lookup.put("key1", "value1");
lookup.put("key2", "value2");
lookup.put("key3", "value3");
Map<String, String> nameValuePair = new HashMap<String, String>(1);
nameValuePair.put("key1", "");
nameValuePair.put("key2", "");
nameValuePair.put("key3", "");
// Lookup by keys
for (String key: nameValuePair.keySet()){
String value = lookup.get(key);
logger.info("key: " + key + " value: " + value);
nameValuePair.put(key, value);
}
Instead of logging inside the loop, log the information outside the loop.
// Lookup table
Map<String, String> lookup = new HashMap<String, String>(1);
lookup.put("key1", "value1");
lookup.put("key2", "value2");
lookup.put("key3", "value3");
Map<String, String> nameValuePair = new HashMap<String, String>(1);
nameValuePair.put("key1", "");
nameValuePair.put("key2", "");
nameValuePair.put("key3", "");
// Lookup by keys
for (String key: nameValuePair.keySet()){
String value = lookup.get(key);
nameValuePair.put(key, value);
}
logger.info(nameValuePair);
Read also various performance articles here.
stf | Jan 16, 2009 | Reply
I think the main point is more.
Don’t waste cpu resource if you don’t need to log
if (logger.isInfoEnabled()) {
logger.info(“logging information”) ;
logger.info(“logging information again”);
}