Tag: log4j

Achieving Separate application level logging in OpenShift using Log4j On JBossAS7

Hi,

In this article, we will discuss about apllication level logging in Openshift. It is always good to have separate application logs, so that it becomes easier for troubleshooting and monitoring.  As we know there are several ways to do it, but we are going to use log4j right now. You would need to download log4j from apache site :

http://logging.apache.org/log4j/1.2/download.html

Below are the steps to achieve separate application level logging :

Step-1 : We will create a small test war file and call it as “log4jtest.war”

log4jtest.war

– WEB-INF
– classes
– TestLog.java (Developers will kill me for placing this here :P)
– log4j.properties
– /com/mpinfo/test/servlet/TestLog.class (my package structure along with class file)
– lib
– log4j.jar
– web.xml
– META-INF
– jboss-deployment-structure.xml
– index.jsp

Now the content of above files :

# index.jsp :

 This is a test page to demonstarte a test with log4j application level logging.
<h3> <a href="TestLog">Click here to Invoke Logger Servlet</a>

# TestLog.java :

package com.mpinfo.test.servlet;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

public class TestLog extends HttpServlet
{
	//private Logger logger = Logger.getLogger(this.getClass().getName());

	private Logger logger = Logger.getLogger("test");

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		logger.info("from log4j=== test log4j log");
		logger.debug("from log4j=== test log4j debug log");
		logger.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
    	{
    		ArrayList ar = new ArrayList();
    		ar.add(new Integer("1"));
    		ar.add(new String("2"));

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

    	out.close();
	}
}

We are generating error in above program to make sure the logging works.

# log4j.properties :


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=/var/lib/stickshift/871lw2a5e1234f5b90da0754977bc176/log4jtest/logs/MyApp.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=%p %t %c - %m%n

Basically “/var/lib/stickshift/871lw2a5e1234f5b90da0754977bc176/log4jtest/logs/” is the default log directory for this application on Openshift, you can check yours by doing ssh to Openshift. You can refer my previous article : How to connect to Openshift Server from command line ??

# jboss-deployment-structure.xml :

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

There is a catch here, JBoss AS7 uses “java.util.logging” package, but the container allows to use other logging mechanism, but the package need to be mentioed inside “jboss-deployment-structure.xml”.

Step-2 :

Assuming that you already have a domain on Openshift, we will proceed with creating an app. Navigate to your project directory and run below command :

$ rhc app create -a log4jtest -t jbossas-7

Step-3 : Step 2 will create a “deployments” directory, now copy your war file to here :

.
$ cp log4jtest.war /log4jtest/deployments/
.

Step-4 : As it is an exploded war we need to create a blank file as “log4jtest.war.dodeploy”

$ touch log4jtest.war.dodeploy

Step-5 : Remove pom.xml file, as we are not performing any build :

$ cd /log4jtest/

$ git rm -f pom.xml

Step-6 : Now lets sync our local repository to Openshift repository :

$ rsync -avz /log4jtest/deployments/ @log4jtest-.rhcloud.com:~/log4jtest/repo/deployments

for example :

$ rsync -avz /OpenShift/log4jtest/deployments/ 871lw2a5e1234f5b90da0754977bc176@log4jtest-testdomain.rhcloud.com:~/log4jtest/repo/deployments
Enter passphrase for key '/root/.ssh/libra_id_rsa':
sending incremental file list
./
.gitkeep
log4jtest.war.dodeply
log4jtest.war/
log4jtest.war/index.jsp
log4jtest.war/index.jsp~
log4jtest.war/META-INF/
log4jtest.war/META-INF/jboss-deployment-structure.xml
log4jtest.war/META-INF/jboss-deployment-structure.xml~
log4jtest.war/WEB-INF/
log4jtest.war/WEB-INF/jboss-web.xml.txt
log4jtest.war/WEB-INF/jboss-web.xml~
log4jtest.war/WEB-INF/web.xml
log4jtest.war/WEB-INF/web.xml~
log4jtest.war/WEB-INF/classes/
log4jtest.war/WEB-INF/classes/Log4jInit.java~
log4jtest.war/WEB-INF/classes/TestLog.java
log4jtest.war/WEB-INF/classes/TestLog.java~
log4jtest.war/WEB-INF/classes/log4j.properties
log4jtest.war/WEB-INF/classes/log4j.properties~
log4jtest.war/WEB-INF/classes/mylog4j.properties~
log4jtest.war/WEB-INF/classes/com/
log4jtest.war/WEB-INF/classes/com/mpinfo/
log4jtest.war/WEB-INF/classes/com/mpinfo/test/
log4jtest.war/WEB-INF/classes/com/mpinfo/test/servlet/
log4jtest.war/WEB-INF/classes/com/mpinfo/test/servlet/TestLog.class
log4jtest.war/WEB-INF/lib/
log4jtest.war/WEB-INF/lib/log4j-1.2.15.jar

sent 364677 bytes  received 393 bytes  22125.45 bytes/sec
total size is 405159  speedup is 1.11

Step-7 : Hit the url from browser :

http://log4jtest-.rhcloud.com/log4jtest/

Step-8 : tail the application logs from Openshift server (need to do ssh to Openshift server)

[log4jtest-testdomain.rhcloud.com deployments]> tail -50f /var/lib/stickshift/871lw2a5e1234f5b90da0754977bc176/log4jtest/logs/MyApp.log
INFO http-127.6.205.129-127.6.205.129-8080-1 test - from log4j=== test log4j log
ERROR http-127.6.205.129-127.6.205.129-8080-1 test - from log4j=== test log4j error log
ERROR http-127.6.205.129-127.6.205.129-8080-1 test - from log4j=== error===Index: 2, Size: 2

And we are done :), stay high on OpenShift !!

Thanks,
MiddlewareMagic Team


Application level log4j.xml and logging in JBoss AS7

Hi,

Log4j or any logging framework is very useful entity of any enterprise application, So that we can have a separate Application level logging using our own version of log4j.jar or any other logger framework version.

In this demonstration we will see how to use the log4j logging inside our Web Application, with it’s own version of “log4j.xml” file. We will also talk about the following points:

In this example we will mainly focus on following points

Point-1). How to use the “log4j.xml” which is placed inside “${YOUR_WAR}/WEB-INF/classes” directory.

Point-2). How to avoid using the JBoss provided logging framework or How to exclude the “org.apache.log4j” module provided by JBoss with the help of “${YOUR_WAR}/META-INF/jboss-deployment-structure.xml” file.

Point-3). Where to place your own version of “log4j.jar” file inside your WAR file. “${YOUR_WAR}/WEB-INF/lib”

Point-4). The Source code of this Demo can be downloaded from the following link (Git Repository):
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/ApplicationLevelLog4jDemo

Another Demo (uploaded on 26 Nov 2012) at EAR level.
https://github.com/jaysensharma/MiddlewareMagicDemos/tree/master/EAR_Level_Log4jDemo

Developing WAR with it’s own logging

Step-1). Here we are using JBoss AS7.1 Final release latest build “jboss-as-7.1.0.Final” which can be downloaded from the following link: http://www.jboss.org/jbossas/downloads

Step-2). Create a directory with the name “src” somewhere in your file system like “/home/userone/ApplicationLevelLog4jDemo/”. Inside the “src” directory we are going to place our all source code and xml files for development.

Step-3). Write a simple “index.jsp” file inside “/home/userone/ApplicationLevelLog4jDemo/src” as following:

<html>
<head>
<title>Application Level Log4j Demo In JBoss AS7</title>
</head>
<body>

      <form action="TestServlet" method="Get">
           Choose Log Level : 
                           <select name="logLevel">
                              <option>TRACE</option>
                              <option>DEBUG</option>
                              <option>WARN</option>
                              <option selected="true">INFO</option>
                           </select>
                           <BR>
           Enter Mesage to be logged: <input type="textarea" name="logMessage"/> <BR>
           <input type="submit" name="submit" value="log the message"/> 
      </form>
      
</body>
</html>

Step-4). Now we will write a simple Servlet based on Servlet3.0 specification with name “TestServlet.java” inside “/home/userone/ApplicationLevelLog4jDemo/src” as following

package servlets;
import java.io.IOException;
import java.io.PrintWriter;

//servlet-api
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//log4j
import org.apache.log4j.Logger;

@WebServlet(value="/TestServlet")
public class TestServlet extends HttpServlet 
  {
	private static final long serialVersionUID = 1L;
        private static Logger logger = null;

        public void init() throws ServletException {
         logger= Logger.getLogger(TestServlet.class);   
        }

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			PrintWriter out=response.getWriter();
                        String logLevel=request.getParameter("logLevel");
                        String logMessage=request.getParameter("logMessage");
                        out.println("<html><head><title>Log4j Logging Demo</title></head><body>");
                        if(logLevel.equals("TRACE"))
                           {
                             out.println("["+logLevel+"] "+logMessage+" (logged inside log file).");
                             logger.trace(logMessage);
                           }
                        if(logLevel.equals("DEBUG"))
                           {
                             out.println("["+logLevel+"] "+logMessage+" (logged inside log file).");
                             logger.debug(logMessage);
                           }
                        if(logLevel.equals("INFO"))
                           {
                             out.println("["+logLevel+"] "+logMessage+" (logged inside log file).");
                             logger.info(logMessage);
                           }
                        if(logLevel.equals("WARN"))
                           {
                             out.println("["+logLevel+"] "+logMessage+" (logged inside log file).");
                             logger.warn(logMessage);
                           }

                        out.println("<BR><BR><a href="index.jsp"> Want a different logging level? </a></body></html>");
		     } 
                 catch (Exception e) 
                     {
			e.printStackTrace();
		     }
	}
}

Step-5). The most important part, We will need to write the following kind of “log4j.xml” file inside “/home/userone/ApplicationLevelLog4jDemo/src” as following :

NOTE: We need to just make sure that once the application is build this file should be present inside the ${WAR_NAME}/WEB-INF/classes directory.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
     <appender name="AppLogAppender" class="org.apache.log4j.DailyRollingFileAppender">
         <param name="DatePattern" value="'.'yyyy-MM-dd"/>
	 <param name="File" value="${jboss.server.log.dir}/MyAppLogsFile.log" />
	 <param name="Append" value="false"/>
         <layout class="org.apache.log4j.PatternLayout">
	     <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
	 </layout>
     </appender>

     <!-- The "category" represents the package names of your Application APIs which we want to log -->
     <category name="servlets">
         <priority value="TRACE"/>
     </category>

     <root>
         <priority value ="TRACE"/>
         <appender-ref ref="AppLogAppender"/>
     </root>
 </log4j:configuration>

Step-6). Download and place the desired version of log4j jar (like “log4j-1.2.16.jar”) inside the “/home/userone/ApplicationLevelLog4jDemo/src”. So that after building the application this jar will be available inside the “${WAR_NAME}/WEB-INF/lib” directory.

Step-7). Now the most important part, In order to avoid using JBoss provided logging APIs, we need to place the following kind of “jboss-deployment-structure.xml” file inside “/home/userone/ApplicationLevelLog4jDemo/src” so that we can exclude the jboss logging APIs for our application and our application can use it’s own version of logging APIs.

NOTE: after building the WAR file make sure that the “jboss-deployment-structure.xml” is present inside the “META-INF” directory of your WAR file. Example: ${WAR_NAME}/META-INF/jboss-deployment-structure.xml

<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
  <deployment>
    <exclusions>
        <module name="org.apache.log4j" />
    </exclusions>
  </deployment>
</jboss-deployment-structure>

NOTE: If you are using JBossAS 7.1.2 then In order to avoid this ClassCastException you will need to include the following System property in your JBoss -Dorg.jboss.as.logging.per-deployment=false
If you are using JBoss AS7.1.2 and not using the above mentioned “jboss-deployment-structure” file then you will see the following kind of exception at the time of deployment of your WAR:

18:05:41,507 ERROR [stderr] (MSC service thread 1-3) log4j:ERROR Could not create an Appender. Reported error follows.
18:05:41,509 ERROR [stderr] (MSC service thread 1-3) java.lang.ClassCastException: org.apache.log4j.DailyRollingFileAppender cannot be cast to org.apache.log4j.Appender
18:05:41,509 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.parseAppender(DOMConfigurator.java:248)
18:05:41,510 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.findAppenderByName(DOMConfigurator.java:176)
18:05:41,510 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.findAppenderByReference(DOMConfigurator.java:191)
18:05:41,510 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.parseChildrenOfLoggerElement(DOMConfigurator.java:523)
18:05:41,510 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.parseRoot(DOMConfigurator.java:492)
18:05:41,511 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.parse(DOMConfigurator.java:1001)
18:05:41,511 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:867)
18:05:41,511 ERROR [stderr] (MSC service thread 1-3) 	at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:794)
18:05:41,512 ERROR [stderr] (MSC service thread 1-3) 	at org.jboss.as.logging.LoggingConfigurationProcessor.deploy(LoggingConfigurationProcessor.java:111)
18:05:41,512 ERROR [stderr] (MSC service thread 1-3) 	at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:116)
18:05:41,513 ERROR [stderr] (MSC service thread 1-3) 	at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
18:05:41,513 ERROR [stderr] (MSC service thread 1-3) 	at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
18:05:41,513 ERROR [stderr] (MSC service thread 1-3) 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
18:05:41,514 ERROR [stderr] (MSC service thread 1-3) 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
18:05:41,514 ERROR [stderr] (MSC service thread 1-3) 	at java.lang.Thread.run(Thread.java:722)

Step-8). Now in order to build and deploy the above application we will write a very simple ant build script “build.xml” inside “/home/userone/jboss-as-7.1.0.Final/standalone/TESTING/ApplicationLevelLog4jDemo” as following:

<project name="Log4j_Basic_Demo" default="deploy">
<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Final" />
<property name="jboss.module.dir" value="${jboss.home}/modules" />
<property name="basedir" value="." />
<property name="tmp.dir" value="tmp" />
<property name="output.dir" value="build" />
<property name="src.dir" value="src" />
<property name="war.name" value="Log4jDemo.war" />
 
        <path id="jboss.classpath">
             <fileset dir="${jboss.module.dir}">
                 <include name="**/*.jar"/>
             </fileset>
        </path>
 
        <target name="init">
           <delete dir="${output.dir}" />
           <mkdir dir="${output.dir}" />
           <delete dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}" />
           <mkdir dir="${tmp.dir}/WEB-INF/lib"/>
           <mkdir dir="${tmp.dir}/WEB-INF/classes"/>
           <mkdir dir="${tmp.dir}/WEB-INF/META-INF"/>
           <mkdir dir="${tmp.dir}/META-INF"/>
        </target>
 
        <target name="build" depends="init">
           <javac srcdir="${src.dir}" destdir="${tmp.dir}/WEB-INF/classes"  includes="*.java" classpathref="jboss.classpath" />
           <copy todir="${tmp.dir}/WEB-INF/classes">
                <fileset dir="${src.dir}" includes="**/*.java"/>
           </copy>
           <copy file="${src.dir}/index.jsp" tofile="${tmp.dir}/index.jsp"/>   

           <!-- Make sure to place the "log4j.xml" file inside ${WAR_NAME}/WEB-INF/classes  directory--> 
           <copy file="${src.dir}/log4j.xml" todir="${tmp.dir}/WEB-INF/classes"/>

           <!-- Make sure to place the "log4j-1.2.16.jar" file inside ${WAR_NAME}/WEB-INF/lib  directory--> 
           <copy file="${src.dir}/log4j-1.2.16.jar" todir="${tmp.dir}/WEB-INF/lib"/>

           <!-- Using this file we are going to satisfy the log4j dependency without directly placing the log4j.jar inside "WEB-INF/lib"-->
           <copy file="${src.dir}/jboss-deployment-structure.xml" todir="${tmp.dir}/META-INF"/> 

           <jar jarfile="${tmp.dir}/${war.name}" basedir="${tmp.dir}" compress="true"/> 


           <copy file="${tmp.dir}/${war.name}" tofile="${output.dir}/${war.name}"/>
           <delete includeEmptyDirs="true">
              <fileset dir="${tmp.dir}"/>
           </delete>
        </target>
 
        <target name="deploy" depends="build">
            <echo message="*******************  Deploying the WAR file ${war.name} *********************" />
            <echo message="********** ${output.dir}/${war.name} to ${jboss.home}/standalone/deployments **********" />
            <copy todir="${jboss.home}/standalone/deployments/">
                <fileset dir="${output.dir}/">
                  <include name="${war.name}"/>
                </fileset>
            </copy>
            <echo message="*******************  Deployed Successfully   *********************" />
        </target>
</project>

NOTE: The only change in the above file you need to do is to change the “jboss.home” directory path in the second line of the above script to point to your own JBoss AS7 directory.

Step-9). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:

For Unix Based OS:
export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH

For Windows Based OS:
set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%

Step-10). Now once the PATH is set In the command/Shell prompt you can move inside the directory “/home/userone/jboss-as-7.1.0.Final/standalone/TESTING/ApplicationLevelLog4jDemo” and then run the ant to build & deploy the webapplication. by running the command “ant deploy”

[userone@localhost ApplicationLevelLog4jDemo]$ ant
Buildfile: build.xml

init:
   [delete] Deleting directory /home/userone/ApplicationLevelLog4jDemo/build
    [mkdir] Created dir: /home/userone/ApplicationLevelLog4jDemo/build
    [mkdir] Created dir: /home/userone/ApplicationLevelLog4jDemo/tmp
    [mkdir] Created dir: /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/lib
    [mkdir] Created dir: /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/classes
    [mkdir] Created dir: /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/META-INF
    [mkdir] Created dir: /home/userone/ApplicationLevelLog4jDemo/tmp/META-INF

build:
    [javac] Compiling 1 source file to /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/ApplicationLevelLog4jDemo/tmp
     [copy] Copying 1 file to /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/classes
     [copy] Copying 1 file to /home/userone/ApplicationLevelLog4jDemo/tmp/WEB-INF/lib
     [copy] Copying 1 file to /home/userone/ApplicationLevelLog4jDemo/tmp/META-INF
      [jar] Building jar: /home/userone/ApplicationLevelLog4jDemo/tmp/Log4jDemo.war
     [copy] Copying 1 file to /home/userone/ApplicationLevelLog4jDemo/build

deploy:
     [echo] *******************  Deploying the WAR file Log4jDemo.war *********************
     [echo] ********** build/Log4jDemo.war to /home/userone/jboss-as-7.1.0.Final//standalone/deployments **********
     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Final/standalone/deployments
     [echo] *******************  Deployed Successfully   *********************

BUILD SUCCESSFUL
Total time: 2 seconds

Step-11). Now you will able to access your application. “http://localhost:8080/Log4jDemo/index.jsp” try to access the servlet and then check the “${jboss.server.log.dir}/MyAppLogsFile.log” file to see if the application level logging is happening properly.

.
.
Thanks
Middleware Magic Team


Application level log4j logging with it’s own log4j.xml file and filtering in JBoss AS6

Hi,

Many times while deploying our application on application servers we want to have a separate application level logging in a separate application log file, Also many times it is desired to have a separate log4j configuration file inside the application so that additional configurations will not be required in order to deploy that application on Server.

In this demonstration we will see the following things
Requirement-1). How can an application will have it’s own “MyLog4j.xml” file ?
Requirement-2).
How to apply log filtering some of the unwanted messages will not appear in the log?

Step1). Create a directory somewhere in your file system with some name like “C:/TestAppLevelLog.war”. Then create “WEB-INF/classes” directories inside “C:/TestAppLevelLog.war”

Step2). Write your won log4j configurations like “MyLog4j.xml” file inside “C:/TestAppLevelLog.war/WEB-INF/classes” directory as following:

<?xml version="1.0" encoding="UTF-8" ?>
   <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
     <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
           <appender name="appender" class="org.apache.log4j.FilAS6pender">
	       <param name="File" value="${jboss.server.log.dir}/MyAppLogs.log"/>
	       <param name="Append" value="true"/>
                <layout class="org.apache.log4j.PatternLayout">
	           <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
	        </layout>
	   </appender>

      <root>
          <priority value ="trace"/>
          <appender-ref ref="appender"/>
      </root>
    </log4j:configuration>

NOTE: Here application log file name is “MyAppLogs.log” which will be created insdside the JBoss’s “$PROFILE/log” directory of your server. It is good practicde to avoid hardcoding of absolute paths.

Step3). Now in order to write some messages in the log file we will write the following kind of code inside JSP/servlet, Suppose it is “index.jsp” which we are going to place inside “C:/TestAppLevelLog.war” directory.

<%@ page import="java.net.*,org.apache.log4j.xml.DOMConfigurator,org.apache.log4j.Logger" %>
<%
		java.net.URL url=Thread.currentThread().getContextClassLoader().getResource("MyLog4j.xml");
		DOMConfigurator.configure(url);

               //NOTE: If u use log4j.properties file (Not the XML file) then use  PropertyConfigurator
               //PropertyConfigurator.configure(url);

		Logger logger = Logger.getLogger(this.getClass());
		logger.info(" This is an information message");
		logger.error("This is an error message");
		logger.fatal("This is a fatal error message");
		logger.warn("I want this message should not appear in the app logs...SOME STRING");

		out.println("<h1>Please check your application log file...for above logging.</h1>");
		out.println("<h3>If logging is not happening then make sure that the MyLog4j.xml file is placed inside WEB-INF/classes.</h3>");
%>

Step4). Now place some “web.xml” file inside your applications “C:/TestAppLevelLog.war/WEB-INF” directory like following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

</web-app>

Step5). Now depoy your application “TestAppLevelLog.war” inside “$PROFILE/deploy” directory and then access the application. like http://localhost:8080/TestAppLevelLog/index.jsp and then check the log file “$PROFILE/log/MyAppLogs.log” you will see following kind of messages logged:

19:51:39,465 [http-127.0.0.1-8080-1] INFO -  This is an information message
19:51:39,466 [http-127.0.0.1-8080-1] ERROR - This is an error message
19:51:39,466 [http-127.0.0.1-8080-1] FATAL - This is a fatal error message
19:51:39,466 [http-127.0.0.1-8080-1] WARN - I want this message should not appear in the app logs...SOME STRING

NOTE: If you want to filter out some special lines containing some specific strings should to appear in the application logs in that case you can apply the “org.apache.log4j.varia.StringMatchFilter” filter inside your “MyLog4j.xml” file as following:

<?xml version="1.0" encoding="UTF-8" ?>
   <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
     <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
           <appender name="appender" class="org.apache.log4j.FilAS6pender">
	       <param name="File" value="${jboss.server.log.dir}/MyAppLogs.log"/>
	       <param name="Append" value="true"/>
                <layout class="org.apache.log4j.PatternLayout">
	           <param name="ConversionPattern" value="%d [%t] %p - %m%n"/>
	        </layout>

              <filter class="org.apache.log4j.varia.StringMatchFilter">
                  <param name="StringToMatch" value="SOME STRING" />
                  <param name="AcceptOnMatch" value="false" />
              </filter>

	   </appender>

      <root>
          <priority value ="trace"/>
          <appender-ref ref="appender"/>
      </root>
    </log4j:configuration>

Now you will see that the line which was containing “SOME STRING” string will not appear in the logs:

19:51:39,465 [http-127.0.0.1-8080-1] INFO -  This is an information message
19:51:39,466 [http-127.0.0.1-8080-1] ERROR - This is an error message
19:51:39,466 [http-127.0.0.1-8080-1] FATAL - This is a fatal error message

NOTE:

JBoss AS6 already provides “log4j.jar” so you need not to place it separately inside “C:/TestAppLevelLog.war/WEB-INF/lib” directory.

.
.
Thanks
Middleware Magic Team


Copyright © 2010-2012 Middleware Magic. All rights reserved. |