Saturday, March 28, 2015

Logging for Jax-RS webapps.

1. Add logs to custom log file using java logging API.

i) Define a logging.peroperties file (sample file in webapp https://github.com/ajithnv/blog_resources/blob/master/webapp-logging/jaxrs_basic/src/main/conf/logging.properties) property description http://developer.classpath.org/doc/java/util/logging/FileHandler.html

handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler
#Log file name in home directory(GNU)
java.util.logging.FileHandler.pattern=%h/jaxrs_basic%u.log
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

#Size of the log file
java.util.logging.FileHandler.limit=500000

#Number of log file
java.util.logging.FileHandler.count=1

#Append logs to original file without creating new one
java.util.logging.FileHandler.append=true

ii. You need to add this file (logging.peroperties) to WEB-INF/classes location inside the war file.(This is configured in pom.xml file in sample webapp https://github.com/ajithnv/blog_resources/blob/master/webapp-logging/jaxrs_basic/pom.xml )

2. Add logs to wso2carbon.log file (If deployed on WSO2  Server ).

i. Copy the log4j.properties file to war file (WEB-INF/classes) which can be found in <server_home>repository/conf

3.  Initialize the logger.
//This it to write to logs to external file
 private static Logger customLog = Logger.getLogger(CustomerService.class.getName());
//This us to write to logs to wso2carbon.log file
private static final Log wso2Log = LogFactory.getLog(CustomerService.class);
4. Java Imports required.
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 @GET
    @Path("/customers/{id}/")
    public Customer getCustomer(@PathParam("id") String id) {
        System.out.println("----invoking getCustomer, Customer id is: " + id);

        customLog.info("get customer information for " + id);
        wso2Log.info("get customer information for "+ id);

        long idNumber = Long.parseLong(id);
        Customer c = customers.get(idNumber);
        return c;
    } 
(https://github.com/ajithnv/blog_resources/blob/master/webapp-logging/jaxrs_basic/src/main/java/demo/jaxrs/server/CustomerService.java)

5. Build the war file using maven and deploy. (Eg: WSO2 Application Server).

6. Invoke the sample REST service using curl
curl -X  GET "http://localhost:9763/jaxrs_basic/services/customers/customerservice/customers/123"
7. You can find the logs in following locations.

i) wso2carbon.log (wso2_server/repository/log/wso2carbon.log)
ii) jaxrs_basic0.log (created in home dir)
iii) Start up console