Logging is so important in software development. In simple projects, JDK logging can be a solution, but not for enterprise applications because it lacks flexibility. This tutorial will help you know how to do logging with SLF4J and Logback.
Related Article: Logging with SLF4J
Contents
I. Introduction
1. SLF4J
There are many famous frameworks to be used for logging: Log4j, Logback, java.util.logging… If we wanna change the logging framework without affecting Java code, SLF4J is the good choice.
SLF4J, the Simple Logging Facade for Java, serves as a simple facade or abstraction for many logging frameworks above. The layer we apply logging is independent from logging implementation. We only have to choose the configuration of logging system.
For details, please read previous post: Logging with SLF4J.
2. Logback
Logback, designed by Log4j‘s founder, is intended as a successor to the popular Log4j project. It builds upon a decade of experience gained in designing industrial-strength logging systems. So, Logback is faster and has a smaller footprint than all existing logging systems, sometimes by a wide margin.
Logback improve many advantages over Log4j:
– faster implementation
– logback-classic speaks SLF4J natively
– configuration files in XML or Groovy
– automatic reloading of logging configuration
– better filter
– automatic compression of archived log files
– stack traces with packaging data (such as jar file)
– automatic removal of old log archives
Logback Architecture
Logback has three modules: logback-core, logback-classic and logback-access:
– core module lays the groundwork for the other two modules
– classic module extends core, it is likely improved version of log4j. Logback-classic implements SLF4J API so we can easily switch between Logback and other logging frameworks.
– access module integrates with Servlet containers to provide HTTP-access log functionality.
II. Overview
1. Technologies
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)
2. Project Structure
3. Step to do
– Create Maven project
– Add Dependencies & Plugins
– Create XML Configuration for Logback
– Create MainApplication Class
– Run Application & Enjoy Result
III. Practice
1. Create Maven project
– Open Spring Tool Suite, on Menu, choose File -> New -> Maven Project.
– Check Create a simple project, choose Workspace Location and click Next.
– Fill all fields in Artifact group box, then click Finish.
2. Add Dependencies & Plugins
Open pom.xml, add:
<dependencies> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <!-- Logback's ch.qos.logback.classic.Logger class is a direct implementation of SLF4J's org.slf4j.Logger interface --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </pluginManagement> </build> |
3. Create XML Configuration for Logback
Under src/main/resources, add logback.xml file:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} >> %-3relative [%thread] %-5level %logger{25} - %msg %n</Pattern> </encoder> </appender> <appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender"> <File>E:/tmpLog/logback.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>E:/tmpLog/logback-%d{yyyy-MM-dd---HH-mm}.log</FileNamePattern> <maxHistory>10</maxHistory> </rollingPolicy> <encoder> <Pattern>%d{HH:mm:ss} [%thread] %-5level %logger - %msg %n</Pattern> </encoder> </appender> <logger name="com.javasampleapproach.logback" level="DEBUG" additivity="false"> <appender-ref ref="consoleAppender" /> <appender-ref ref="rollingFileAppender" /> </logger> </configuration> |
Logback delegates task of writing a logging event to appenders. This example uses 2 kinds of appender: ConsoleAppender and RollingFileAppender (inherit from FileAppender).
– ConsoleAppender appends on the console (System.out or System.err) with the help of an encoder specified by Pattern.
– FileAppender appends log events into a file. The target file is specified by the File option.
– RollingFileAppender extends FileAppender can rollover log files. For example, it can log to a file named logback.log, then change its logging target to another file when meeting a certain condition. This example uses RollingFileAppender with rollingPolicy to rollover log file every minute with 10 minutes history keeping.
For details about Pattern, please visit Conversion Word.
In this example,
<Pattern>%d{HH:mm:ss.SSS} >> %-3relative [%thread] %-5level %logger{25} - %msg %n</Pattern> |
will create a result like this:
19:34:44.751 >> 367 [main] INFO c.j.logback.MainApp - <info> Java Sample Approach |
4. Create MainApplication Class
Under package com.javasampleapproach.logback, create MainApp.java:
package com.javasampleapproach.logback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainApp { static Logger logger = LoggerFactory.getLogger(MainApp.class); public static void main(String[] arg) { logger.info("<info> Java Sample Approach"); logger.trace("<trace> Java Sample Approach"); logger.error("<error> Java Sample Approach"); logger.debug("<debug> Java Sample Approach"); System.err.println("<System print> Java Sample Approach"); } } |
Using SLF4J is easy, we get a logger, and log messages at some logging levels (TRACE, DEBUG, INFO, WARN, ERROR). Because we set level="DEBUG"
, so the logger only appends these logging levels: DEBUG, INFO, WARN, ERROR.
You can understand SLF4J deeply in previous article: Logging with SLF4J.
5. Run Application & Enjoy Result
– Config maven build:
clean install
– Run project with mode Java Application
– Check results in Console Screen:
19:41:18.290 >> 346 [main] INFO c.j.logback.MainApp - <info> Java Sample Approach 19:41:18.337 >> 393 [main] ERROR c.j.logback.MainApp - <error> Java Sample Approach 19:41:18.337 >> 393 [main] DEBUG c.j.logback.MainApp - <debug> Java Sample Approach <System print> Java Sample Approach |
– Open E:/tmpLog/logback.log:
19:41:18 [main] INFO com.javasampleapproach.logback.MainApp - <info> Java Sample Approach 19:41:18 [main] ERROR com.javasampleapproach.logback.MainApp - <error> Java Sample Approach 19:41:18 [main] DEBUG com.javasampleapproach.logback.MainApp - <debug> Java Sample Approach |
– We can also see more rolling log files in E:/tmpLog/ folder:
IV. Source Code
Last updated on June 4, 2017.