Logging using Log4j and SLF4J in Java SE application

Logging using Log4j and SLF4J in Java SE application.

First you must download Log4j and SLF4J frameworks. Next put to project's classpath these JARs: log4j, slf4j-api and slf4j-log4j. Log4J is your logging framework. SLF4J-API is SLF4J framework. SLF4J-LOG4J is a bridge between SLF4J and LOG4J.

Log4j needs also some configuration, where is defined what will be logged and where will be logging information saved. This configuration is typically done using file with filename log4j.properties or log4j.xml. Don't bother about configuration in these files, yet. I will explain it later. Log4j will search for these files in classpath. So put into src file log4j.properties. Btw. it can be elsewhere, in this case you must run your application with -log4j.configuration="file_name".

Logging is done using object of type Logger. Create private static final Logger logger = LoggerFactory.getLogger(ClassName.class).

Now we can finally do some logging. It is done using these methods of class Logger:

  • debug
  • trace
  • info
  • warn
  • error

Error method is used for error messages, debug method is used for debugging code etc.

used log4j.properties file:

log4j.rootLogger=INFO, stdout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n