This document provides best practices for logging, including:
- Use SLF4J and Logback for logging to avoid unnecessary message construction
- Get organized with named loggers to identify components and ensure shared loggers
- Choose proper logging levels like ERROR, WARN, INFO, DEBUG to log appropriately
- Be concise and descriptive with log messages, including relevant context and values instead of everything
- Tune the log pattern and use MDC for additional context
- Log method arguments and returns at DEBUG/TRACE levels for debugging
- Log external interactions and exceptions properly without unnecessary details
2. Logging Best Practices
What is Logging?
Why Logging is important?
What are Logging Best Practices?
3. Logging Best Practices
Use the appropriate tools for the job
o SLF4J : A façade for different logging tools which
can be plugged without any code change
o Advantages:
o Parameter Substitution
o No need for isDebugEnabled
o MDC (Map Diagnostic Context)
o Logback is recommended as an
implementation
4. Logging Best Practices
Cost of constructing the message parameter, regardless of
whether the message will be logged or not.
Avoid the cost of parameter construction
Better yet, use parameterized messages
logger.debug(“Number: " + i + " is " + String.valueOf(entry[i]));
if(logger.isDebugEnabled()) {
logger.debug(“Number: " + i + " is " +
String.valueOf(entry[i]));
}
logger.debug(“Number: {} is {}" i , String.valueOf(entry[i]));
5. Logging Best Practices
Get organized with named loggers
o Which component wrote a specific message
to the log
o Declare the logger both static and final to
ensure every instance of a class shares the
logger object
static final Logger logger =
LoggerService.GetLogger(“ac.components.WidgetClass");
6. Logging Best Practices
Choose proper logging levels
ERROR - Something terribly wrong had happened
- No system can tolerate items logged on this level
WARN - The process might be continued, but take extra caution
- Need attention
INFO - Important business process has finished
- each action that changes the state of the application
significantly
DEBUG - Developers stuff
- When can not use debugger tool
TRACE - Very detailed information, only for development but on
production
7. Logging Best Practices
Do you know what you are logging?
o Don’t generate NPE in log statements
o Use ‘id’ of domain objects
o Implement ‘toString()’ method for domain objects
o Use ‘Arrays#deepToString’
o And read your logs often to spot incorrectly
formatted messages
log.debug("Processing request with id: {}", request.getId());
log.debug("Returning users: {}", users);
8. Logging Best Practices
Avoid side effects
o Avoid log too much or improperly use toString() and/or string
concatenation
o Use SLF4J ‘Parameter Substitution’ feature
try {
log.trace("Id=" + request.getUser().getId()
+ " accesses " + manager.getPage().getUrl().toString())
} catch(NullPointerException e) {
}
9. Logging Best Practices
Be concise and descriptive
o Log files should be readable, clean and
descriptive
o Avoid logging everything
o Don’t use magic numbers
o Log values, numbers, ids and include their
context
o Not to log passwords and any personal
information
10. Logging Best Practices
Be concise and descriptive
log.debug(“Message processed”);
log.debug(msg.getJMSMessageID());
log.debug("Message with id '{}' processed",
msg.getJMSMessageID());
if(message instanceof TextMessage){
//...
}Else{
log.warn("Unknown message type");
}
11. Logging Best Practices
Tune your pattern
o In Logback
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppend
er">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread][%logger{0}]
%m%n</pattern>
</encoder>
</appender>
12. Logging Best Practices
Tune your pattern
o Use meaningful messages relevant to the
context
o Mapped Diagnostic Context (MDC)
2009-06-0508:15:23]INFO] User credentials entered
2009-06-0508:15:23]WARN] Incorrect PIN
2009-06-0508:15:37]INFO] User credentials entered
2009-06-0508:15:37]INFO] User credentials validated
2009-06-0508:15:46]INFO] Cash withdrawal requested
2009-06-0508:15:47]ERROR] Communication failure
Acme.ATM.Integration.ServerException: Unable to connect to bank server
...
13. Logging Best Practices
Log method arguments and return values
o It is always better to have too much rather
than too few logging statements
o Your code should be covered with logging
routines as it is with unit tests
o Use DEBUG or TRACE levels
14. Logging Best Practices
Watch out for external systems
o Log every piece of data that comes out from
your application and gets in
o Be extra careful when integrating with
external systems and prepare to pay that
cost
o Use different log levels
15. Logging Best Practices
Log exceptions properly
o Avoid logging exceptions
o Not all exceptions are errors
o Log OR wrap and throw back
Try {
//….
Catch (Exception e) {
log.error(“IO Exception”, e);
Throw new MyCustomException(e);
}