0% developed

Java Logging

From Wikibooks, open books for an open world
Jump to navigation Jump to search

(Fancy TimePlot image here)

Usages for logs:

  • Allowing programs to indicate emergency situations to external programs which can then investigate and take action.
  • Provide timestamped markers for performance analysis.
  • Provide information about what is being processed for later forensic analysis.
  • Timestamps for events.


Logging in programming is one of the areas where the code may literally have been written years before the generated information is needed, and where you have very little or no idea what you might be needing to know at that time. If you could foresee it, you could have coded around it back then.

There is a need for a wiki-based reference helping programmers to create better logs. The focus will not be a comprehensive overview, but a "Best practice"-approach using slf4j and logback/java.util.logging.Logger depending on scenario.

Contents[edit | edit source]

Quick start for the impatient[edit | edit source]

  1. Download and unpack the latest release of SLF4J from http://slf4j.org/download.html
  2. Put slf4j-api-X.Y.Z.jar and slf4j-simple-X.Y.Z.jar on your classpath.
  3. Use Logger log = LoggerFactory.getLogger(this.getClass()) and log.info("At {} with {}", a, b); to log information.

((SAMPLE CODE))


Logging: Why, How, What, Where?[edit | edit source]

    1. SAMPLE Java program with print statements.
    1. Output from said java program.

One of the first things new Java programmers learn is to use System.out.println("....") to see "inside" their program, and frequently this results in a lot of information being printed every time the program runs. Some information is very important and require human action, and some are just trivial indications that a library is working, and some include a stack trace. For advanced programs with multiple threads active, the individual messages may even be mixed together so that "Message 1" and "Message 2" turn into "MMessagessag 1e 2". Also you may need the log in a file and not System.out (which for some platforms are not even available).

    1. SAMPLE Java program as before but with slf4j statements.
    1. Resulting logfiles.






Generating log entries[edit | edit source]

Saving log entries for later[edit | edit source]

Analyzing log entries later[edit | edit source]

Background[edit | edit source]