Logging Best Practices
Tips for Proper Application Logging
- Use the appropriate tools for logging. SLF4J is the best logging API available, mostly because of a great pattern support.
- Declare the logger to be both static and final to ensure that every instance of a class shares the common logger object.
- Better to use logging only to log
- method entry
- method exit
- root cause message of exceptions that are handled at the exception's origin point.
- SLF4J provides logging levels for you.
- ERROR – something terribly wrong had happened, that must be investigated immediately. No system can tolerate items logged on this level.
Example: NPE, database unavailable, mission critical use case cannot be continued. - DEBUG – Developers tool to keep the track of the flow of operation in the application.
- WARN – the process might be continued, but take extra caution.
Standard levels of Log4j are ordered as
ALL < TRACE < DEBUG < INFO < WARN <ERROR < FATAL < OFF
- ERROR – something terribly wrong had happened, that must be investigated immediately. No system can tolerate items logged on this level.
- Be concise and descriptive. Exactly specify the log message error so that it reflects what the method does.
In try catch block, use logger.error("Message about name and purpose of the method.", e). - Use logger.debug("") to show the flow of the operations (name of method and what it does) after logical operations in a method with an appropriate message.
This helps to easily figure out where the application is stuck. - Avoid side effects. Logging statements should have no or little impact on the application’s behavior.
- Handle exception before sending response to client.
Log exceptions properly, just once and log it close to its origin
try { }catch (Exception e){
log.error(
"Error reading configuration file"
, e);
throw new RuntimeException("Error reading configuration file: " + fileName, e);
}- Logs easy to read, easy to parse
if your application produces half GB of logs each hour, no man and no graphical text editor will ever manage to read them entirely.
This is where old-school grep, sed and awk come in handy. If it is possible, try to write logging messages in such a way, that they could be understood both by humans and computers,
e.g. avoid formatting of numbers, use patterns that can be easily recognized by regular expressions, etc.