Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

  2. 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 continuedWARN – the process might be continued, but take extra caution. Actually I always wanted to have two levels here: one for obvious problems where work-around exists (for example: “Current data unavailable, using cached values”) and second (name it: ATTENTION) for potential problems and suggestions.

    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. 

  3. Be concise and descriptive. Exactly specify the log message error so that it reflect reflects what the method does. 
    i.e. 
    In try catch block, use logger.error("Message about name and purpose of the method.", e).

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

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

    1.  Log exceptions properly

        
      try { }

      catch (Exception e){
          log.error("Error reading configuration file", e);   
               throw new RuntimeException("Error reading configuration file:  " + fileName, e);
            }

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