Logging Best Practices

Tips for Proper Application Logging

  1. Use the appropriate tools for logging. SLF4J is the best logging API available, mostly because of a great pattern support.

  2. Declare the logger to be both static and final to ensure that every instance of a class shares the common logger object.

  3. Better to use logging only to log 
    1. method entry
    2. method exit
    3. root cause message of exceptions that are handled at the exception's origin point.

  4. SLF4J provides logging levels for you.

    1. 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.

    2. DEBUG – Developers tool to keep the track of the flow of operation in the application.

    3. 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

  5. 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).

  6. 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.   

  7. Avoid side effects. Logging statements should have no or little impact on the application’s behavior.

  8. Handle exception before sending response to client.

  9.  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);
          }

  10. 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 grepsed 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.