Logging is a pretty much underrated but especially while working on communicational applications it is a must and doing it proper can save a lot of time and makes you look good. For years i’ve used a lot of different logging libraries, some i coded myself some third parties. In the things that i’ve tried out using SLF4J with LOG4J seems to be my favorite thou a bit complicated in start, it’s proven to be highly customizable therefore making things a lot more easier once you get the gist of it.

SLF4J Concrete Bindings

Here you can see the bindings of SLF4J with different systems. If you are going to use SLF4J at first glance this may look a bit complicated but it is pretty useful. Since we are going to use LOG4J with SLF4J first thing you need is to have the noted libraries(slf4j-api.jar, slf4j-log412.jar, log4j.jar) under your classpath folder. Also remember that you shouldn’t have more then 1 binding library in your classpath.

Next you’ll need to create a log4j.properties file in your classpath to tell log4j how to log your entries. Before we proceed there are some things you need to know about Log4j like Loggers,Appenders,Layouts etc. These are different components of LOG4J all serving to a purpose, a Logger(also considered as a “Category”) is seperate channel of logging if you might say. You can seperate different topics in different Categories/Loggers to maintain clarity. Also this maybe applied in an hierarchical manner where such categories as “alicanhasirci.posts” and “alicanhasirci.comments” can exist. Also different categories have different appenders. This means you can append anything you like to entries such as timestamps, class names, log levels etc. Setting the behaviour of logger is another thing where you can tell it write to screen, or write to file or even write to a daily rolling file.

Here is an example log4j.properties file:

log4j.rootLogger=INFO, STDOUT
log4j.logger.alicanhasirci.posts=INFO, ALICANHASIRCI_POSTS

#STDOUT APPENDER
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%d{HH:mm:ss,SSS}: %m%n

#ALICANHASIRCI_POSTS APPENDER
log4j.appender.ALICANHASIRCI_POSTS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ALICANHASIRCI_POSTS.File=alicanhasirci.posts.log
log4j.appender.ALICANHASIRCI_POSTS.layout=org.apache.log4j.PatternLayout
log4j.appender.ALICANHASIRCI_POSTS.layout.ConversionPattern=%d{HH:mm:ss,SSS}: %m%n