BASIC LOGGING
BEST PRACTICES
THINK TWICE ABOUT THE LOGGING LEVEL
AVOID SYSTEM.OUT.PRINTLN
Logging frameworks are:
- Faster
- Configurable
- Flexible
The shell is your friend (blame command):
workspace$ grep -irl -C3 --include '*.java' 'out.println' *
DON'T HIDE STACK TRACES
Avoid these forms:
The correct way is:
logger.error("Exception message", ex);
logger.error("Exception: " + ex);
logger.error("Exception: " + ex.getMessage());
YOU CAN LOG EXCEPTIONS TO AN SPECIAL LOG FILE
try {
...
} catch (Exception ex) {
logger.error("Message");
stackTracesLogger.error("Message", ex);
}
AVOID TO BUILD HEAVY MESSAGES IF LOGGING IS DISABLED
if (logger.isDebugEnabled()) {
logger.debug(buildVeryHeeeeeeavyMessage());
}
DON'T ADD INFO LOG4J GIVES YOU FOR FREE
Instead add configuration (log4j.xml):
<appender ...>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{yyyy-MM-dd HH:mm:ss,SSS} %5p [%t] %c{1} - %m%n"/>
</layout>
</appender>
logger.error("[TheClassName.theMethodName] The message");
DON'T CLUTTER REQUEST WITH DIAGNOSTIC ATTRIBUTES, INSTEAD USE THREAD LOCAL
Use the MDC/NDC API (E.g. from Servlet Filter):
Then log MDC attributes through ConversionPattern:
%X{'httpId'} ... MDC attribute
%x ... NDC
MDC.put('httpId', UUID.randomUUID.toString());
Logging Best Practices
By Rafael Luque
Logging Best Practices
- 2,343