log4j in web application

Ads
 

log4j in web application

Hi all,

I am new to log4j. I want to use log4j in my web application. I need to write the debug,info,warn into a file. But i don't know how to do the same. Please send one example with explaination and how to get the logger object in web application.

Thanks suresh.

View Answers

August 4, 2011 at 10:30 AM

Please visit the following link:

Log4j Examples


January 9, 2012 at 5:15 PM

static final Logger logger=Logger.getLogger(HelloWorld.class);
public static void main(String args[]) throws IOException
    {
    FileAppender fileAppender=new FileAppender(new PatternLayout(),"service.txt");
        logger.addAppender(fileAppender);
        BasicConfigurator.configure();
        logger.debug("Debug Message."); 
        logger.info("Info Message.");
}

This function will write logs messages in 'service.txt' file.
for this purspose you need to have log4j.properties file configured as

log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=/data/dev/newworkspace/log4jTry/src/com/anm/log/log.txt
log4j.appender.rollingFile.MaxFileSize=2MB
log4j.appender.rollingFile.MaxBackupIndex=2
log4j.appender.rollingFile.layout = org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%p %t %c - %m%n
log4j.rootLogger = INFO, rollingFile

ans by 4p3


February 29, 2012 at 11:22 AM

// program by Nishanth Thomas - InSolutions Global Bangalore

// example class file

package com.logs;

import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession;

import org.apache.log4j.BasicConfigurator; import org.apache.log4j.FileAppender;

import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout;

import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator;

public class Logscollected {

  static Logger log = Logger.getLogger(Logscollected.class);

public static void logscollection(Exception e, HttpServletRequest request) throws IOException{

  HttpSession session = request.getSession();

    String  exceptiondetail = ‚??‚?? ;

     //create a folder in your application config and place log4j.xml file there  and       
               // get path by the following;

      String strPath =  request.getRealPath("config");

      DOMConfigurator.configure(strPath+"/"+"log4jexp.xml");

      //create log4j.xml file as give name like  shown above log4jexp;

 try{

      ////  /* Get the Stack Trace messages //////
      e = ((e==null)?((Exception)request.getAttribute("Exception")):e);

        StackTraceElement stem[]=e.getStackTrace();

  for(int i=0;i<stem.length;i++){
        if (!exceptiondetail.equals(""))
                    exceptiondetail += "\n";
                exceptiondetail += "\t";

    exceptiondetail=exceptiondetail+stem[i].toString();

       }

          log.debug(exceptiondetail);
                  //log.info(e);
                    // log.warn("Here is some WARN");
                    //  log.info(object);
          log.error(e);

          //  log.fatal("Here is some FATAL");

    }catch(Exception e1){
        e1.printStackTrace();
    }
  }

}

In the catch of any servlet call that function like this

 try{

//     Some code‚?¶‚?¶‚?¶‚?¶

 }

 catch(Exception e)
    {

                // Logs collection log 4j------------------------

        Logscollected.logscollection(e,request);

        //---------------------------

   }

Now Finally

Lo4j.xml here we renamed to log4jexp.xml to avoid conflicts with server log4j.xml file palce log4jexp.xml in config folder ( here I used)


<--configure path according to your requrmts to save log file -->

<appender name="daoAppender" 
   class="org.apache.log4j.RollingFileAppender">   
    <param name="maxFileSize" value="100KB" />   
    <param name="maxBackupIndex" value="2" />   
    <param name="File" value="${jboss.server.home.dir}/deploy/myexampleprj.war/serverlogs/serverlogs.txt" />   
    <layout class="org.apache.log4j.PatternLayout">   
        <param name="ConversionPattern"  
               value="%d{dd-MMM-yyyy HH:mm};%5p %c %m%n" />   
    </layout>   
</appender>   

  <--configure path according for diff packge to your requrmts to save log file -->   

<!--appender name="appAppender"  
          class="org.apache.log4j.RollingFileAppender">   
    <param name="maxFileSize" value="100KB" />   
    <param name="maxBackupIndex" value="2" />   
    <param name="File" value="${jboss.server.home.dir}/deploy/myexampleprj.war/serverlogs/serverlogs.txt" />   
    <layout class="org.apache.log4j.PatternLayout">   
        <param name="ConversionPattern"  
               value="%d{ABSOLUTE} %5p %c{1}: %m%n " />   
    </layout>    
</appender-->   

<!‚??package name given in category here com is the package give package name  -->    

<!--category name="com.ex.actions">     
    <priority value="DEBUG"/>     
    <appender-ref ref="appAppender"/>       
</category-->

<category name="com">     
    <priority value="DEBUG"/>     
    <appender-ref ref="daoAppender"/>       
</category>    

<root>   
    <!--     
    <appender-ref ref="appAppender" />   
    <appender-ref ref="daoAppender" />   
    -->    
</root>

Ads









Related Tutorials/Questions & Answers:
log4j in web application
log4j in web application  Hi all, I am new to log4j. I want to use log4j in my web application. I need to write the debug,info,warn into a file... and how to get the logger object in web application. Thanks suresh
simple web applications using log4j
simple web applications using log4j  i am getting java.lang.NoClassDefFoundError: org/apache/log4j/Logger and javax.servlet.ServletException: Error instantiating servlet class Sample exceptions when trying to execute. this is my
Advertisements
web application
web application  what is lazy loading in web based application
web application
web application  Dear friend, could u plz tell me wats difference bt web server,application server,container with thanks praveen
Log4j
Log4j  what is the use of log4j in realtime?   Please visit the following link: Log4j Tutorials
log4j
log4j  explain about log4j with example ?   Please visit the following link: log4j Tutorials
LOG4J
LOG4J  HOW AND WHERE TO FIND org.prot.appserver.config.Configuration; PACKAGE TO IMPORTIN LOG4J PREOGRAM
Web application
Web application  in web applications which file will execute first either servlet or jsp
web application
web application  Develop a web application to print back the inputs from the user(name, date of birth, address). The solution should have a JSP file which accepts the user‚??s name and sent to Servlets which puts the name
some queries pertaining to use of log4j for logging in a java application-
some queries pertaining to use of log4j for logging in a java application- ... that as well. (4) The application in which I want to use log4j has multiple... appender, that too in such a way that the actual log file (to which log4j should
connecting to timesten in web application
connecting to timesten in web application  Please give me the steps connecting to timesten in web application. Am using jsp
what is the difference between distributed application and web application?
what is the difference between distributed application and web application?  what is the difference between distributed application and web application
WEB APPLICATION IN JSP
WEB APPLICATION IN JSP  Can you help me with a JSP code which can search and update existing data in mysql database
java web application - Ant
tell me the steps to build and deploy a small web application on MyEclipse?(like... a directory structure for a Web application. a)Create a WEB-INF directory... deployment descriptor in the WEB-INF directory for the Web application. 5
Java web Application
Java web Application  Hi! I have developed a java web application project using netbean IDE with glassfish server. My question is how to create a runnable file from this. How can we make it to a single file? I think it is war
Quartz in web-application
Quartz in web-application  As I am new to Quartz i don't know how to use it in web-application.I am able to run it in eclipse as a stand alone application i had tried out some example but am not able to succeed any help
Web application - business layer
Web application - business layer   Design your business layer to be stateless, which helps to reduce resource contention and increase... with a stateless Web application business layer. If you perform business
Web Application Common Architecture
Web Application Common Architecture  Hi, Any one tell me, while project constructing , how they architect it which means using some layers and specify importance of layers. And also best way to follow program flow
servlet question on web application
servlet question on web application   how to write a programg on the web application. create two modules like admin and customer. customer can registrate with user id and password. after finishing of his registration he'll get
php mysql web application tutorial
php mysql web application tutorial  How to create a simple php mysql web application? Please post an example or tutorial
ssl comunication between a desktop application and a web application
ssl comunication between a desktop application and a web application  Hi Lusiano, I am trying to implement a ssl comunication between a desktop application and a web application. can you please share code with me. Please
HTS Web Application Framework
HTS Web Application Framework       The HTS Web Application Framework is a PHP and Javascript based framework designed to make simple web applications easy to design and implement
draw chart in web application
draw chart in web application  how to draw bar chat from the record store in database? i.e. draw the bar chart according to selected record
creating a friendly url for web application
creating a friendly url for web application  Hi all, I don't know how to create a friendly url for a web application. Please help me to resolve this problem. Thanks, Suresh
error in web application
error in web application  In your application when i am trying to execute it from the below page <%@ page language="java" import="java.util....; We are providing you another application. Check it. 1)application.jsp
Introduction of Web Application
The application based on web is stored on a remote server and they can be accessed through web browser
Web based workflow application example?
Web based workflow application example?  Hello there, Can anyone please send a sample project which is a web-based java workflow application? If it is built using Spring, Struts or JSF Framework it would be wonderful. If you
Version of log4j>log4j dependency
List of Version of log4j>log4j dependency
DIFFERENCE BETWEEN APPLICATION SERVER AND WEB SERVER
DIFFERENCE BETWEEN APPLICATION SERVER AND WEB SERVER  What is the difference between application server and web server
Steps to log4j configuration in Struts2
Steps to log4j configuration in Struts2  Hi... any tel me each step for configure log4j in struts2 application
create web application using maven
In this section, you will learn to create a web application using maven

Ads