Maven

Maven SLF4J integration example

In this example, we shall show you how to integrate Apache Maven with SLF4J. Apache Maven is a software project management and comprehension tool. It provides powerful features like superior dependency management including automatic updating and transitive dependencies.

It follows the principle of convention over configuration, due to which one can start with a minimal configuration and sensible defaults will be provided for all the missing configuration.

Maven uses central repositories where various artifacts like JAR files can be hosted. It comes with a mechanism that resolves all project dependencies from these central repositories. So effectively you are resolved from keeping and providing JAR files on your project’s classpath.

Maven only needs a file called ‘pom.xml’ where one can define dependencies as we will be seeing in the example below. Once you choose to build the project, these dependencies will be automatically fetched from central repository and put on your application’s classpath.

SLF4J is a simple facade over various logging frameworks. It gives abstraction and therefore makes it easier to change logging implementations later on in a software project.It is a very stable library and is actively used by various open source software like Apache Camel, ActiveMQ, Solr and EhCache etc. For this example we will be using Apache Maven 3.2.5 and SLF4J 1.7.5. The example is compilable on Java 5 and above.

1. Creating Maven Project

Initially, we will be creating a bare minimum maven project. This will be a command line Hello World application.Later on we will be integrating SLF4J in it.Once you have maven installed and running on your machine, issue following command from command line.

    mvn archetype:generate -DgroupId=com.javacodegeeks -DartifactId=MvnSlf4J -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Maven will be downloading all dependencies from the default Maven Central repository and creating a bare minimum hello world project for us. Once the above command have completed, Maven would have generated a really small pom.xml file and src folder for us. There is a single class called ‘App.java’ in the src. If you compile and run application at this point. You will get a command line Hello World message.

2. Integrating SLF4J

To integrating SLF4J, we need to make following changes to pom.xml

  • Adding SLF4J jar file to classpath. We will be using simple logger for purpose of this example. Simple logger logs to console by default. However this can be easily changed to a production capable logging framework like log4j or logback later on in the development stage. All logging calls to slf4j will remain same even in such case.

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>JavaCodeGeeks</groupId>
    	<artifactId>MvnSlf4J</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>MvnSlf4J</name>
    	<url>http://maven.apache.org</url>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    	</properties>
    
    	<dependencies>
    
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-simple</artifactId>
    			<version>1.7.5</version>
    		</dependency>
    
    	</dependencies>
    </project>
    
  • Adding maven exec plugin. This is a helpful plugin for console based applications. Using this plugin we will be invoking our Java application main method from command line. Here are the contents of final pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>JavaCodeGeeks</groupId>
    	<artifactId>MvnSlf4J</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>MvnSlf4J</name>
    	<url>http://maven.apache.org</url>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.slf4j</groupId>
    			<artifactId>slf4j-simple</artifactId>
    			<version>1.7.5</version>
    		</dependency>
    	</dependencies>
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.codehaus.mojo</groupId>
    				<artifactId>exec-maven-plugin</artifactId>
    				<version>1.2.1</version>
    				<executions>
    					<execution>
    						<goals>
    							<goal>java</goal>
    						</goals>
    					</execution>
    				</executions>
    				<configuration>
    					<mainClass>com.javacodegeeks.mvnslf4j.App</mainClass>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    </project>
    
    
  • Using slf4j in our hello world application. We will be modifying recently created hello world application in this step.

    package com.javacodegeeks.mvnslf4j;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * Hello world for slf4J!
     *
     */
    public class App {
    	public static void main(String[] args) {
    		Logger logger = LoggerFactory.getLogger(App.class);
    
    		logger.info("This is an information message");
    		logger.error("this is a error message");
    		logger.warn("this is a warning message");
    	}
    }
    
    
  • Building and running project. As the pom.xml file is changed, we need to rebuild the project so that maven can download all new dependencies using following command.

                cd MvnSlf4J
                mvn clean install
                mvn exec:java
    
  • Output
    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------------------------------------------------------------
    [INFO] Building MvnSlf4J 0.0.1-SNAPSHOT
    [INFO] ------------------------------------------------------------------------
    [INFO]
    [INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) > validate @ MvnSlf4J >>>
    [INFO]
    [INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) < validate @ MvnSlf4J <<<
    [INFO]
    [INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ MvnSlf4J ---
    [com.javacodegeeks.mvnslf4j.App.main()] INFO com.javacodegeeks.mvnslf4j.App - Th
    is is an information message
    [com.javacodegeeks.mvnslf4j.App.main()] ERROR com.javacodegeeks.mvnslf4j.App - t
    his is a error message
    [com.javacodegeeks.mvnslf4j.App.main()] WARN com.javacodegeeks.mvnslf4j.App - th
    is is a warning message
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 0.703 s
    [INFO] Finished at: 2015-02-22T23:52:45+05:30
    [INFO] Final Memory: 6M/123M
    [INFO] ------------------------------------------------------------------------
    
    

5. Download source code

Download
You can download the full source code of this example here: Maven Slf4J Integration Example

Arpit Gautam

Arpit has graduated from Computer Science and Engineering Department from the Institute of Technology and Management Gurgaon. He is working in enterprise product development since a decade and worked on desktop, mobile and server side applications using java. During his studies, he participated in various coding contests and technical paper presentations. He is working as a lead Software Engineer in Workforce Management domain where he is mainly involved with projects based on Java application and C++ system programming. He is curious about writing agile code which can adapt as business changes. He likes to experiment with open source technologies and java tech stack in his spare time.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button