Fancy UI

All About Crazy IT Stuff

Configure LogBack Logging with Spring

with 5 comments

LogBack is a new API for logging created by the same author of Log4j(a newer implementation, it is like a new version), during this article I’m going to show how to integrate it and use it on a Spring project. On this tutorial I assume you are using a simple Spring ROO project which will prepare all the structure of the project for you, for more information see : http://www.springsource.org/spring-roo.

First of all you need to create the logback.xml (hold the configuration appenders like log4j.properprties) file in src/main/resources :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d %5p | %t | %-55logger{55} | %m %n</pattern>
        </encoder>
    </appender>

    <logger name="test.myapp.repos">
        <level value="INFO" />
    </logger>

    <logger name="org.springframework">
        <level value="INFO" />
    </logger>

    <root>
        <level value="INFO" />
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

The second step is to configure Maven dependencies and add LogBack required libraries:

<-- Properties Settings -->
<properties>
    <roo.version>1.1.0.RELEASE</roo.version>
    <spring.version>3.0.5.RELEASE</spring.version>
    <aspectj.version>1.6.10</aspectj.version>
    <slf4j.version>1.6.1</slf4j.version>
    <logback.version>0.9.26</logback.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>

<-- Dependencies Settings -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${slf4j.version}</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>${logback.version}</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-core</artifactId>
    <version>${logback.version}</version>
</dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-access</artifactId>
    <version>${logback.version}</version>
</dependency>

You need to get rid of all Log4j dependencies in the Maven pom.xml generated by Spring ROO, clean every single dependency related to logging before you add the code provided to set up LogBack.

For using the logger on a  class you are developing, you need to create a static instance of it and use normally as you use the Log4J, the only difference is the implementation and configuration code of LogBack Vs Log4j. On Logback.xml your class must be scanned for the logger to work.

package test.myapp.repos; /*This package figures on LogBack.xml*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyTestClass {
    static Logger logger = LoggerFactory.getLogger(ItemController.class);
    ...

    public void create(String args) {
        logger.debug("My Args Is => " + args);
    }
    ...
}

There is another sophisticated way of injecting the logger on a Spring bean, this can be achieved by developing a custom BeanPostProcessor which will automatically inject the Logger on fields annotated with @Log (this is a custom annotation we created) instead of instantiating the manually the logger as described earlier.

/** Custom @Logger annotation **/
@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface Log { }

/** LoggerPostProcessor => Custom Spring BeanPostProcessor **/
public class LoggerPostProcessor implements BeanPostProcessor {

    public Object postProcessAfterInitialization(Object bean, String beanName) throws
        BeansException {
        return bean;
    }

    public Object postProcessBeforeInitialization(final Object bean, String beanName)
          throws BeansException {
        ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
                @SuppressWarnings("unchecked")
                public void doWith(Field field) throws IllegalArgumentException,
                    IllegalAccessException {
                    ReflectionUtils.makeAccessible(field);

                    //Check if the field is annoted with @Log
                    if (field.getAnnotation(Log.class) != null) {
                        Log logAnnotation = field.getAnnotation(Log.class);
                        Logger logger = LoggerFactory.getLogger(bean.class);
                        field.set(bean, logger);
                    }
                }
        });

        return bean;
    }
}

/** Usage on a Spring Bean **/
@Component
public class MyBeanImpl implements MyBean {
    /** Not manual set up code **/
    @Log Logger myLogger;
    ...
}

The last thing to do is to declare this new BeanPostProcessor on you applicationContext.xml file :

<!-- The Logger Injector -->
 <bean id="LogginInjector" class="org.test.utils.LoggerPostProcessor" />

For more information about why to switch to LogBack, see : Why switch to LogBack.

About these ads

Written by imrabti

December 12, 2011 at 2:36 pm

Posted in Logging, Spring

Tagged with , ,

5 Responses

Subscribe to comments with RSS.

  1. Hey,

    Thanks for the wonderful post on logback integration with Spring. After learning about logback from java code geeks, I always wanted to do this, but never did it until I stumbled upon your article.

    I followed the steps and voila it worked except at one place. I have AspectJ integrated with my Spring Project and the logger is giving me a NPE. Since SpringRoo internally uses aspects, I wasn’t hoping to get this. Do you know whats happening out there?

    Murali

    December 16, 2011 at 5:36 pm

  2. From what you said LogBack is working, the only thing that doesn’t work is the @Log annotation to inject Logger on the variable instead of instantiating it ?

    imrabti

    December 17, 2011 at 9:12 am

  3. [...] Configure LogBack Logging with Spring – May 6, 2012 – 3:28 am | By admin | Posted in tips | Comments (0) ← Bookmarks for May 5th from 01:56 to 15:07 [...]

  4. [...] Configure LogBack Logging with Spring – May 5, 2012 – 4:50 pm | By admin | Posted in tips | Comments (0) ← Bookmarks for May 4th [...]

  5. What plugin are you using for your code blocks and syntax highlighting?

    charlesrgould

    December 2, 2013 at 4:57 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: