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 property description

handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler
#Log file name in home directory(GNU)

#Size of the log file

#Number of log file

#Append logs to original file without creating new one

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 )

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

i. Copy the 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;
    public Customer getCustomer(@PathParam("id") String id) {
        System.out.println("----invoking getCustomer, Customer id is: " + id);"get customer information for " + id);"get customer information for "+ id);

        long idNumber = Long.parseLong(id);
        Customer c = customers.get(idNumber);
        return c;

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