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. 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>









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
log4j
log4j  explain about log4j with example ?   Please visit the following link: log4j Tutorials
Log4j
Log4j  what is the use of log4j in realtime?   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  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
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
log4j - Log4J
log4j  could u pls help me out regarding the log4j coding   http://www.javaworld.com/javaworld/jw-12-2004/jw-1220-toolbox.html Thanks
Log4J - Log4J
Log4J  What is the use of Log4j? where does it use? Log4j is using for debuging ur code. Its does the same thing as System.out/System.err do. i.e to trace out ur program   Log4j is using for debuging ur code.Its does
log4j - Log4J
log4j  give me explanation about log4j,junit? how i hvae to use them   Hi mamatha, In Log4J, if you log a message at DEBUG level, and the current Appender is set to only log messages of INFO level and above
web application to internet - JavaMail
web application to internet  how to connect my web application to internet
web application - WebSevices
web application  how to create a j2ee web application using java abstract class & interface
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
Web application security - Security
Web application security  Hi, Expert how to hide url in webpage or fix the url in every web page in java.Please give any suggestion or idea
Directory structure of a web application
Directory structure of a web application   Explain the directory structure of a web application.    The directory structure of a web application consists of two parts. A private directory called WEB-INF.ADS
Web application - Spring
Web application  I need one simple complete web application example using springs with database connection,i saw ur demo but it is not succfient.can u send to [email protected] am a beginner
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
Web application - JSP-Servlet
Web application   Helo can you please help me in knowing how to use jsp/servlets which allows users to post question in a forum so that other users can also view the question and respond to it.For instance your application here
web application security - Security
web application security  Hello, Experts how can i prevent that a copy url cannot run in same brower or different browser again .Please Suggest any idea i already check if a session is null then forwward a login page
Flex web application
Flex web application  Hi.... How can i develop web based applications in Flex? please give me the whole procedure so i can make web apps in flex..... Thanks
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
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
Maven Repository/Dependency: log4j | log4j
? How to create Maven Web Application in Eclipse? Maven 3 Tutorial...Maven Repository/Dependency of Group ID log4j and Artifact ID log4j. Latest version of log4j:log4j dependencies. # Version
Version of log4j>log4j dependency
List of Version of log4j>log4j dependency
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
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
Steps to log4j configuration in Struts2
Steps to log4j configuration in Struts2  Hi... any tel me each step for configure log4j in struts2 application
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
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
Log4j error - Log4J
Log4j error  Error while running tomcat server. SEVERE: Exception sending context initialized event to listener instance of class...-logging.jar and log4j-1.2.15.jar to your application. This will solve the issue
To publish jsp web application in intranet
To publish jsp web application in intranet  I am making web application in jsp with netbean. I want to publish this web application in LAN/Intranet.So by publishing web application it can be access through LAN/Intranet
Web application? - Java Interview Questions
Web application?  What is webapplication?  Hi friend, Any application that uses Web Technologies including web browsers, web servers and Internet protocols is called Web Application. A web application can
Why Struts in web Application - Struts
Why Struts in web Application  Hi Friends, why struts introduced in to web application. Plz dont send any links . Need main reason for implementing struts. Thanks Prakash
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
Quartz web application - Java Beginners
Quartz web application  Quartz is not firing jobs as per cron expression in java web application. I set the cron expression as 0/20 * * * * ? and when i load the web application it runs fine but its not firing the job after
Application Server and Web Server - WebSevices
Application Server and Web Server  General difference, Application Server and Web Server  Answer: A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response
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
java web application printing - WebSevices
java web application printing  i have a web-page with a table displayed containing report card of a class of students(visual web JSF APPLICATION created in netbeans 6.0) d problm i hv is i wnt to let dat page be converted
java - Log4J
regarding "LOG4J" and where these are exactly used in realtime application... as posible.   Hi Friend, Log4j is a logging package to help..., an OutputStream, a java.io.Writer etc. Using Log4j it is possible to enable logging
Configuring Log4J
Configuring Log4J  Is it possible to configure xml file in such a way that it has different logging levels for diferent packages in java through Log4J
hi - Log4J
hi  Please give me the clear definition of Log4J and give me the example

Ads