RESTEasy + Tomcat 7 + Log4j Logging Example

RESTEasy is very flexible when comes to logging support. It can work with log4j, slf4j and java.util.logging also. Algorithm used to decide that which logging framework needs to be used is:

  1. If log4j is in the application’s classpath, log4j will be used
  2. If slf4j is in the application’s classpath, slf4j will be used
  3. java.util.logging is the default if neither log4j or slf4j is in the classpath
  4. If the servlet context param resteasy.logger.type is set to JUL, LOG4J, or SLF4J will override this default behavior

In this post, we will learn to log4j with RESTEasy when developing application in tomcat server.

Environment used:

  • Tomcat 7
  • Log4j 1.2.17
  • RESTEasy JAX-RS 2.3.1.GA

Steps to configure log4j

1) Include dependency in project

I am adding maven dependencies. You can choose to include jar file if required.

	<!-- core library -->
	<!-- Log4j -->

2) Add file in classpath

A minimum configuration in log4j file can be this:

log4j.rootLogger=DEBUG, consoleAppender, fileAppender

log4j.appender.consoleAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

log4j.appender.fileAppender.layout.ConversionPattern=[%t] %-5p %c %x - %m%n

3) Use log statements in API methods

Always use “org.jboss.resteasy.logging.Logger” as it is configured using above given algorithm and thus decouple the logging framework dependency from application code completely. It means that if you later decide to use slf4j instead of log4j, you simply need to put slf4j in runtime classpath and remove log4j from classpath. That’s it !!

import org.jboss.resteasy.logging.Logger;

@XmlRootElement(name = "user-management")
public class UserService 
	Logger log = Logger.getLogger(UserService.class); 
    @Path("/users/{id : \d+}")
    public User getUserById(@PathParam("id") Integer id) {"GET API called for id : " + id);
        User user = new User();
        return user;

4) Test the logging

Making call to above RESTFul API will log the events like this:

[http-bio-8080-exec-3] INFO  org.jboss.resteasy.plugins.server.servlet.ConfigurationBootstrap  - Adding scanned resource: com.howtodoinjava.service.UserService
[http-bio-8080-exec-3] DEBUG org.jboss.resteasy.core.SynchronousDispatcher  - PathInfo: /user-management/users/10
[http-bio-8080-exec-3] INFO  com.howtodoinjava.service.UserService  - GET API called for id : 10

Happy Learning !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

2 thoughts on “RESTEasy + Tomcat 7 + Log4j Logging Example”

  1. nice post for beginner to use log4j in RESTFUL API, but can you please show an example on how to get user session using log4j in GET Method?


Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.