Cloud Zone is brought to you in partnership with:

I concentrate on designing and building enterprise software in Java, .NET, and related technologies. I am a strong advocate of the Feature Driven Development (FDD) process, Modeling in Color, and Peer Code Review. I have been developing software since 1995 in Java, C#, Visual Basic, ASP, PHP, and C. My primary focus has been designing and developing web-based applications, although I have worked on my share of client applications, web services, and PL/SQL. Eric is a DZone MVB and is not an employee of DZone and has posted 4 posts at DZone. You can read more from them at their website. View Full User Profile

Application Level Logging in OpenShift

08.05.2012
| 8141 views |
  • submit to reddit

I read a good article tonight about implementing application level logging using log4J, and I thought this concept could be extended and abstracted one level further by making use of the Apache Commons Logging API. Using the Apache Commons Logging API allows the logging implementation to be abstracted away from the application; resulting in application logging code that can be reused even if the logging implementation changes. There has been some criticism of the Commons Logging API for many years, and I will address that by saying the same principle can be applied with a different logging façade like SLF4J.

Enough talking, let’s get started…

Step #1:

First, I created a JBoss AS7 application in OpenShift called “commonslogging”.

Then I opened a command prompt (or terminal),and cloned the Git repository onto my own machine using the Git command specified by OpenShift when creating a project.

Step #2:

Next, I imported the project as a Maven Project in Eclipse using the local Git repository.

image

Figure 1: Import Project into Eclipse

image

Figure 2: Create new Maven Project in Eclipse

Step #3:

Next, you will need to download the Commons Logging API and log4J implementation if you do not already have them. You can find them here:

Next, I added the Commons Logging and log4j dependancies to the Maven pom.xml file.

<dependency>
    <groupid>commons-logging</groupid>
    <artifactid>commons-logging</artifactid>
    <version>1.1.1</version>
</dependency>
<dependency>
    <groupid>log4j</groupid>
    <artifactid>log4j</artifactid>
    <version>1.2.17</version>
</dependency>

Step #4:

Next, expand the /src/main/webapp folder and create a new “index.jsp” file.

Replace the content with the following:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>OpenShift Apache Commons Logging Test</title>
</head>
<body>
    This is a test page to demonstrate a test with Apache Commons
    Logging and log4j application level logging.
    <p>
        <a href="Log4jTest">Click here to Invoke Logger</a>
    </p>
</body>
</html>

You can delete the “index.html” file that was created by the OpenShift application wizard.

Step #5:

Create a new Java class, “Log4jTest.java”, in the /src/main/java folder.

Replace the default content with the following code:

package org.ericsilva.openshift.commonslogging;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

/**
 * Tests the log4j implemenation using Apache Commons Logging API.
 * 
 * @author Eric Silva (ES)
 */
public class Log4jTest extends HttpServlet {

    /**
     * Serialization UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * Logger instance
     */
    private Log log = LogFactory.getLog("test");

    /**
     * {@inheritDoc}
     */
    protected void doGet(
                    HttpServletRequest request,
                    HttpServletResponse response) throws ServletException,
                    IOException {
        log.info("from log4j=== test log4j log");
        log.debug("from log4j=== test log4j debug log");
        log.error("from log4j=== test log4j error log");

        System.out
            .println("from system.out.println==== test system.out.println log");
        System.err
            .println("from system.err.println==== test system.error.println log");

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("from printwriter=== test printwriter log");

        try {
            List<String> ar = new ArrayList<String>();
            ar.add("1");
            ar.add("2");

            log.info("from log4j=== get arraylist index=2" + ar.get(2));
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
            log.error("from log4j=== error===" + e.getMessage(), e);
            System.err.println("from system.err.println=== error==="
                + e.getMessage());
        }

        out.close();
    }
}

Step #6:

Open the “web.xml” file in the /src/main/webapp/WEB-INF folder, and add the following servlet mapping:

<servlet>
    <servlet-name>Log4jTest</servlet-name>
    <servlet-class>org.ericsilva.openshift.commonslogging.Log4jTest</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Log4jTest</servlet-name>
    <url-pattern>/Log4jTest</url-pattern>
</servlet-mapping>

You will need to change the package name of the Log4jTest.java file to the package name you used when creating the file.

Step #7:

Create a new file, ”log4j.properties”, in the /src/main/resources folder.

Paste the following contents into the file:

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger

log4j.rootLogger=INFO, test
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MM/dd HH:mm:ss.SSS}][%p]%c{1}:%L - %m%n
log4j.appender.CONSOLE.Threshold=INFO

# My Application Log
log4j.appender.test=org.apache.log4j.RollingFileAppender
log4j.appender.test.File=logs/application.log
log4j.appender.logfile.Threshold=INFO
log4j.appender.test.MaxBackupIndex=100
log4j.appender.test.MaxFileSize=1Gb
log4j.appender.test.encoding=UTF8
log4j.appender.test.layout=org.apache.log4j.PatternLayout
log4j.appender.test.layout.ConversionPattern=<%d> <%t> <%p> <%F:%L> - %m%n

Step #8:

The final thing we need to do is create a “META-INF” folder in the /src/main/webapp folder and add a “jboss-deployment-structure.xml” descriptor file to tell it to use the Commons Logging API instead of the default “java.util.logging” implementation.

After you create the META-INF folder and XML descriptor, add the following contents to the XML file:

<jboss-deployment-structure>
  <deployment>
    <exclusions>
        <module name="org.apache.commons.logging" />
    </exclusions>
  </deployment>
</jboss-deployment-structure>

Step #9:

Next commit your changes to your local Git repository, and then push the changes back to OpenShift. OpenShift will automatically try to deploy your new code.

Step #10:

Next, open you application’s URL in your favorite browser, e.g. http://commonslogging-ericsilva.rhcloud.com/

Click the link on the page. This will generate an error that will appear in your application log file.

For information on how to connect via SSH to your application for command line access I suggest reading this article.

Happy Coding. I really want to do more with OpenShift.

 

 

 

 

 

 

 

 

Published at DZone with permission of Eric Silva, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)