[WSO2 Application Server] Configure Logging Inside a Web Application

WSO2 Application Server provides a platform to host your web applications and manage them. WSO2 AS supports tenants so you can own your own deployment area inside the server.

In the development phase of a web application, we need to troubleshoot problems, errors. These errors MUST appear in the server console, otherwise essentially the web apps cannot be troubleshooted. If you deploy a web application and do

            System.out.println("TEST");

It will not appear in default log file for WSO2 Application Server ([AS_HOME]/repository/logs/wso2carbon.log). In order to log errors, warnings and debugs you need to log them.

To configure logging in the web application all you need to do is, packing log4j.properties file, which can be found at [AS_HOME]/repository/conf/log4j.properties into the .war file that is built.

Packaging log4j.properties file

If you are using maven, you can use Apache Maven WAR Plugin to build the .war file. The default resource directory for all Maven projects is src/main/resources which will end up in target/classes and in WEB-INF/classes in the WAR. The directory structure will be preserved in the process. Thus, if we place log4j.properties file inside src/main/resources maven will package it nicely. 



Log4j Dependancies


Add following dependency into the pom.xml file


        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>

Add Logging in Java Classes 

Do following imports

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

Then add some log lines as below

        private static final Log wso2Log = LogFactory.getLog(ControllerServlet.class);

        try {

            wso2Log.info("INFO");
            wso2Log.error("ERROR");
            wso2Log.warn("WARN");
            wso2Log.trace("TRACE");

            System.out.println("TEST");

            throw new Exception("this is an exception");

        } catch (Exception e) {
            e.printStackTrace();
            wso2Log.error("This is the caught error" ,e);
        }


Now if you tail wso2carbon.log file you will notice all the logs are there.



Following blog post also has more information on logging inside web applications.
http://www.vitharana.org/2015/03/logging-for-jax-rs-webapps.html









Hasitha Hiranya

No comments:

Post a Comment

Instagram