Advertisement :
   Log In    OR    Register  
  Topics :  
RMI Example

Home >>> Apache Log4j >>> Log4j Example >>> Log4j Tutorial
Struts Tutorials:
Struts2 Tag CheckBoxList
, Checkbox, Iterator, IF
Struts2 Tag Library Example Struts2 Tiles Example Struts2 Tiles I18N Example Struts2 Questions Struts Tiles I18N Example Struts Eclipse MVC Struts2 Tags Struts2 Example and Tutorial Struts MVC Struts2 Validation
Hibernate Tutorials: Hibernate Case Study Class Hierarchy Persist Example Using Hibernate Interceptor Hibernate Questions with Answer Hibernate Many-to-Many Mapping Example Hibernate one-to-many Mapping Example Hibernate and ORM tools Spring Hibernate Example Hibernate SessionFactory Example Hibernate Mapping Class Hierarchy Hibernate Questions Hibernate SessionFactory Questions Spring Hibernate Example: Spring Hibernate Case Study

Written By : Amit
Title :
Common Logging Log4j
Description : Logging Solution using Java Technology
More...


Written By : Amit
Title :
Different logging files Log4j
Description : configuration time using Log4j
More...


Written By : Amit
Title :
How to use Log4j
Description : PatternLayout
More...


Written By : Amit
Title :
Using NDC and Log4j
Description : NDC Push with Log4j
More...


Written By : Amit
Title :
Log4j Example
Description : Log4j Tutorial
More...

Tags/Keywords : Log4j Example,Log4j Tutorial, Log4j article
Author : Amit
Date (Year/Month/Date): 2009-04-19 Log4j example Step by Step Usage :
Log4j Example : A simple way to show possibility of providing
various appenders in a single log4j.properties file

Advertisement :
I have used Three appenders from Log4j 1.2.14, such as ConsoleAppender, FileAppender and JDBCAppender. This example will try to show how to use multiple Logger and combination of appenders for various purpose and depending on logging requirement. Now in this example I shall try to configure three Loggers and three appenders, such as shown below:
log4j.rootLogger=A B C
log4j.logger.A=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %C - %m%n

log4j.logger.B=DEBUG, A2
log4j.appender.A2=org.apache.log4j.FileAppender
log4j.appender.A2.file=sample-log.txt
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=%d [%t] %-5p %C - %m%n

log4j.logger.C=ERROR, A3
log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender
log4j.appender.A3.Driver=org.hsqldb.jdbcDriver
log4j.appender.A3.URL=jdbc:hsqldb:hsql://localhost/
log4j.appender.A3.User=sa
log4j.appender.A3.Password=
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=
       insert into LogTable(log_detail) values('%d [%t] %-5p %C - %m%n')
I shall try to explain this log4j properties file, In this example, there are three loggers with names A, B, C and these loggers are defined in rootLogger property. Each logger has various levels such as for A and B loggers, level is DEBUG and for C logger, Level is ERROR. Logger A has consoleAppender Logger B has FileAppender and Logger C has JDBCAppender. As the value after comma separated level in logger definition, is that of Appender, so Logger A has A1 appender, Logger B has A2 and Logger C has A3 as appender. Each appender has to have some log destination and Layout with pattern. Interestingly for JDBCAppender (in this example, appender A3), database table with insert statement , along with database driver and url with login credential required. But there are ways to provide database Connection from some other DataSource with connection Pooling capabilities as well. This can be done by overriding default JDBCAppender getConnection method. For this example, I have used HSQLDB as database and following Table to hold log messages:
create table LogTable
(log_detail varchar(300))
And the Java Main application is as follows:
import org.apache.log4j.*;

public class TestLog4j
{
    private static Logger logger = Logger.getLogger("B");
    public TestLog4j() {
        testLogging();
    }
    public void testLogging() {
        logger.debug("starting testLogging method....");
        for(int i=0;i<10;i++) {
            logger.info("counting work ..."+i);
        }
        logger.debug("closing testLogging method....");
        logger.error("some error occured....");
    }
    public static void main(String[] args) 
    {
        new TestLog4j();
    }
}
Just notice the RED part in bold above, it shows that I am selecting logger B and with Appender A2. So all DEBUG level logs will go to Log file "sample-log.txt". Now if I want to send all debug logs to filesystem and to database table, then one can use two appenders A2 and A3 with Logger B. like log4j.logger.B=DEBUG, A2, A3 Hope this example helps in understanding a basic usage of Log4j as logging framework.
Advertisement :


	

Commented By ->
Good1234
Is there any ways to configure buffer size for the 
JDBCAppender, in this example?
If Yes, Can you please show me how?

Thanks for this wonderful example.

Commented By ->
Amit
While using Log4j 1.2.x version, JDBCAppender has following
method setBufferSize(int newBufferSize),

reference http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/jdbc/JDBCAppender.html

So I guess by adding following line to the log4j.properties
file, one can set buffer size and subsequently alter 
frequency of writing log statement to database.

log4j.appender.A3=

Can you please try this out and let me know if this works?

Commented By ->
arunlepuru
thanks lot,
very good matter,iam new to java but i what to 
send the error through mail which was held in 
the class and what is the buffersize in log4j

Commented By ->
Amit
One can look at the SMTP appender from Javadoc api
of Log4j 
http://logging.apache.org/log4j/1.2/apidocs/index.html?org/apache/log4j/net/SMTPAppender.html

I think you can read the explaination of buffersize for Log4j 1.2.15,
and use accordingly.
To my understanding this Buffersize is the cyclic buffer of 
events
those are stored in internal buffer before flushing out at some predefined 
numbers reached (as set by the bufferSize attribute in log4j properties for SMTPAppender)

Please correct me if I am wrong.

Commented By ->
Surendrababu
Very useful and precise

thanx a lot amitttttttttttttt

Commented By ->
Amit Ranjan
hi arunlepuru,

With respect to your first question regarding sending an email
when some error (runtime I guess) occurs in any class, I would
suggest you to go through the Apache Log4j Javadoc api, as 
pointed out below:

SMTPAppender

And try to do some sort of prototype using this and you may need
to configure or pass any already configured SMTP server to be used
along with your prototype.

And I think Buffersize is the internal storage capacity to hold
on with log messages, and once the capacity is full, then those logged
 messages are done with as per the configuration setting in log4j.properties file.

Hope this answers your questions.
used all at 
Are you interested in solving a very interesting Technology Stack while Playing this Game          

Please write your Comment on this Matter
(This will be visible if found suitable):
Name: *
Email (will not be displayed): *
Matter: *
18,29
Enter bigger number from above :*
Home >>> Apache Log4j >>> Log4j Example >>> Log4j Tutorial
Visitor/User referred related external URL:
(Visible upon review and approved by this site Administrator)
Referred By Name *:
Resource URL *: (e.g, URL should be starting with http://www.-----.---)
 
Resource Short Description *:
25,23
Enter bigger number from above : *

Please log in to add or reply to any matter<- requires login
Log in or Register
Copyright © 2008-2009, Interview-Questions-Tips-Forum, All Rights Reserved.
CONTACT    PRIVACY POLICY    DISCLAIMER
Terms of Use and Disclaimer :

This web site provides some of the information about various technologies, example 
code, tips, tutorials etc. Like any printed materials, content of these pages may 
become out of date over a period of time. Therefore all visitor/users of this web 
site are requested/advised to refer to the originating parties/sources for the 
latest changes and happenings for detailed information. This information is not 
intended to be a substitute for the original reference provided by the originating 
parties/sources.

By accessing and using this website in any ways, including, without
limitation, browsing the website pages, using any information, using any content and/or 
downloading any materials, you agree to and are bound by the terms of use 
described in this page and Usage Terms and Conditions. 
If you do not agree to all of 
the terms and conditions contained in the terms of use described in this
page and Usage Terms and Conditions, do not use this 
website in any manner. If you are using the website on behalf of your 
employer, you represent that you are authorized to accept these Terms of Use 
on your employer's behalf.

All Trademarks are property of their respective owner. Appropriate measure is being
taken for providing accurate and up-to-date information but like any printed materials,
these blog(s)/contents may eventually be outdated one day, so if you are using any 
of these information, please refer original content/documentation from respective sources. 
And under no circumstances shall the Author of these contents and/or this web site
be liable for any loss, damage, expense incurred or suffered which is claimed to have
occurred because of usage of the contents of this web site.
If you have any questions/queries/feedback/suggestions then please write to this web
site owner at contact.