Understanding Log4J: Components, Configuration, and Usage, Lecture notes of Java Programming

An overview of the log4j logging framework, focusing on its three main components: appenders, loggers, and layouts. It explains how to use different appenders such as consoleappender, fileappender, and writerappender, and discusses the methods of logger class like debug(), warn(), and error(). The document also covers the configuration of log4j using properties file and xml file, as well as the use of basicconfigurator.

Typology: Lecture notes

2011/2012

Uploaded on 08/09/2012

dhanyaa
dhanyaa 🇮🇳

4.7

(3)

60 documents

1 / 11

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Log4JArchitecture‐IntroductiontotheLog4Jarchitecture
InthissectionwewilllearnaboutthearchitecturalcomponentofLog4J.Understandingthearchitecture
ofLog4Jisimportant.
ThreemaincomponentofLog4J
ThearchitectureofLog4Jframeworkislayeredandconsistsofthreemaincomponents.There
componentsoftheLog4Jare:
1. Logger
2. Appender
3. Layout
1.Logger
Loggeristhemostessentialcomponentoftheloggingprocess.Itisresponsibleforcapturingthelogging
information.Thereare5differentloglevelsoftheLogger.ThelevelofLoggerareasfollowing:
Thereare5normallevelsoflogger:
DEBUG:Mostusefultodebuganapplication.
INFO:Itprovidesinformationalmessages.
WARN:Itprovidesthatapplicationmayhaveharmfulevents.
ERROR:Itprovidesthatapplicationhavingerroreventsbutthatmightallowittocontinue
running.
FATAL:Itdenotesthesevereerroreventswhichleadtheapplicationtoabort.
Inaddition,therearetwospeciallevelsalsotheyare:
ALL:Itisintendedtoturnonalllogging
OFF:Itisintendedtoturnofflogging
Youcanalsosettheloggerlevelbyputtingasimplecodelike
logger.setLevel((Level)Level.WARN);

2.AppendersinLog4J:
TheAppenderisresponsibleforpublishingthelogtoadestination.Itcontrolshowtheloggingprovides
theoutput.
Therearefewlistofappenderslistedbelow:
ConsoleAppender
DailyRollingFileAppender
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Understanding Log4J: Components, Configuration, and Usage and more Lecture notes Java Programming in PDF only on Docsity!

Log4J Architecture ‐ Introduction to the Log4J architecture

In this section we will learn about the architectural component of Log4J. Understanding the architecture of Log4J is important. Three main component of Log4J The architecture of Log4J framework is layered and consists of three main components. There components of the Log4J are:

  1. Logger
  2. Appender
  3. Layout 1. Logger Logger is the most essential component of the logging process. It is responsible for capturing the logging information. There are 5 different log levels of the Logger. The level of Logger are as following: There are 5 normal levels of logger:
  • DEBUG : Most useful to debug an application.
  • INFO : It provides informational messages.
  • WARN : It provides that application may have harmful events.
  • ERROR : It provides that application having error events but that might allow it to continue running.
  • FATAL : It denotes the severe error events which lead the application to abort. In addition, there are two special levels also they are:
  • ALL : It is intended to turn on all logging
  • OFF : It is intended to turn off logging You can also set the logger level by putting a simple code like logger.setLevel((Level)Level.WARN); 2. Appenders in Log4J: The Appender is responsible for publishing the log to a destination. It controls how the logging provides the output. There are few list of appenders listed below:
  • ConsoleAppender
  • DailyRollingFileAppender
  • FileAppender
  • RollingFileAppender
  • WriterAppender
  • SMTPAppender
  • SocketAppender
  • SocketHubAppender
  • SyslogAppendersends
  • TelnetAppender ConsoleAppender is used as: ConsoleAppender appender = new ConsoleAppender(new PatternLayout()); FileAppender is used as: FileAppender appender = new FileAppender(new PatternLayout(),"filename"); WriterAppender is used as: appender = new WriterAppender(new PatternLayout(),new FileOutputStream("filename")); 3. Layouts in Log4J: For each Appender it needs to have an associated Layout, which guides how to format the output. The Layout is responsible for formatting the log output in different layouts. User can control the output format by modifying the Log4J configuration file. There are basically three types of Layout:
  1. HTMLLayout : It formats the output in the HTML table
  2. PatternLayout : It formats the output in the conversion pattern
  3. SimpleLayout : It formats the output in a simple manner, it prints the level then place a dash and then the user specified log message. Configuring Log4J For running application using Log4J you need to download the latest version log4j jar file and then add this to the classpath. There are two ways to configure the Log4J one is by using properties file and other by using xml file. Using xml for Log4J is quite popular and it is recommended also. In the next section we will download Log4J libraries, install and then run a small program.

LogExample1.java import org.apache.log4j.Logger; public class LogExample1 { public LogExample() { } static Logger log = Logger.getLogger(LogExample. class ); public static void main(String argsp[]) { log.debug("Here is some DEBUG"); log.info("Here is some INFO"); log.warn("Here is some WARN"); log.error("Here is some ERROR"); log.fatal("Here is some FATAL"); } } log4j.properties log4j.rootLogger=debug, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%5p] %d{mm:ss} (%F:%M:%L)%n%m%n%n This Example shows you how to create a log in a Servlet. Description of the code: Logger.getLogger(): Logger class is used for handling the majority of log operations and getLogger method is used for return a logger according to the value of the parameter. If the logger already exists, then the existing instance will be returned. If the logger is not already exist, then create a new instance. log.info(): This method is used to check that the specified category is INFO enabled or not, if yes then it converts the massage passed as a string argument to a string by using appropriate object renderer of class ObjectRenderer.

log4jexample2.java import org.apache.log4j.Logger; class CustomerOrder { private String productName; private int productCode; private int productPrice; public int getProductCode() { return productCode; } public void setProductCode( int productCode) { this .productCode = productCode; } public String getProductName() { return productName; } public void setProductName(String productName) { this .productName = productName; } public int getProductPrice() { return productPrice; } public void setProductPrice( int productPrice) { this .productPrice = productPrice; } public CustomerOrder(String productName, int productCode, int productPrice) { this .productName = productName; this .productCode = productCode; this .productPrice = productPrice; } } public class Log4jExample2 { private static Logger logger = Logger.getLogger("name"); public void processOrder(CustomerOrder order) { logger.info(order.getProductName()); } public static void main(String args[]) { CustomerOrder order1 = new CustomerOrder("Beer", 101, 20); CustomerOrder order2 = new CustomerOrder("Lemonade", 95, 10); CustomerOrder order3 = new CustomerOrder("Chocolate", 223, 5);

BasicConfigurator.configure(); logger.debug("Hello world."); } } Now after running this code you will get the following output on your console: Output: 0 [main] DEBUG SimpleLog.class ‐ Hello world. where "0" shows time taken in milliseconds from start of program to the logging request. "Hello world" is the message that we have given. SimpleLog.class is the logger name and in bracket [main] is the thread who have invoked logging.

log4j.xml Example

In earlier example you have seen that we can define properties of log4j logging file with the help of log4j.properties. Properties can also be defined within log4j.xml file. You have to add following contents to this XML file. log4j.xml

Log4j looks for **log4j.xml** file first and then go for **log4j.properties** hence you must place both the files in your folder. We use **log4j.xml** since properties file does not provide some advanced configuration options such as **Filter** , some of **ErrorHandlers,** and few advanced **Appenders**. **log4j.properties log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out**

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L ‐ %m%n log4j.rootLogger=debug, stdout Here is our SimpleLog class code: SimpleLog.java import org.apache.log4j.*; public class SimpleLog { static Logger logger = Logger.getLogger("SimpleLog.class"); public static void main(String[] args) { logger.debug("Welcome to Log4j"); } } Output: 13:07:40,875 DEBUG class:5 ‐ Welcome to Log4j

Console Appender in Log4j

In this log4j console appender tutorial you will be introduced with ConsoleAppender which is used in Log4j for appending output on the console each and every time when any info(), debug(), error() method is invoked by the logger. n this log4j console appender tutorial you will be introduced with ConsoleAppender which is used in Log4j for appending output on the console each and every time when any info() , debug() , error() method is invoked by the logger. In our example we have made a class ConsoleAppenderExample. After this we have created a logger object by invoking static method getLogger(). After this we have created an object of ConsoleAppender and to add this logger message we need to add appender to logger. Following code does it for us. "logger.addAppender(conappender)" where conappender is ConsoleAppender's object. Here is the example code for ConsoleAppender example : ConsoleAppenderExample.java import org.apache.log4j.*; public class ConsoleAppenderExample { static Logger logger = Logger.getLogger( "ConsoleAppenderExample.class"); public static void main(String[] args) { ConsoleAppender conappender =

FileAppenderExample.java import org.apache.log4j.*; public class FileAppenderExample { static Logger logger = Logger.getLogger("FileAppenderExample.class"); public static void main(String[] args) throws Exception { FileAppender fileappender = new FileAppender( new PatternLayout(),"output.txt"); logger.addAppender(fileappender); logger.info("Log has been appended to your output.txt"); logger.info("See your output.txt"); } } Compilation and execution of FileAppenderExample class will create "output.txt" file for the first time then will append log events to it. Output:

WriterAppender in Log4j

In our previous section we have seen that we can append log events in simple file (plain/text) file and to the console also. In our previous section we have seen that we can append log events in simple file (plain/text) file and to the console also. If we want to write files then we have to use WriterAppender. WriterAppender appends log events to a Writer or an OutputStream depending on the user's choice. In our example we have created a class WriterAppenderExample. First we need to create logger object and then we have to add appender to it. So we have created an object of WriterAppender and since it requires Writer or OutputStream we are using a file "Writer.html". We have taken layout of HTML format that therefore we have to use HTMLLayout. logger.addAppender(writeappender); will add writerappender to logger and all logging events will be added to this HTML file. Here is the example code for WriterAppenderExample class:

WriterAppenderExample.java

import java.io.; import org.apache.log4j.; public class WriterAppenderExample { static Logger logger = Logger.getLogger("WriterAppenderExample.class"); public static void main(String[] args) { try { FileOutputStream filename= new FileOutputStream("Writer.html"); WriterAppender writeappender = new WriterAppender( new HTMLLayout(),filename); logger.addAppender(writeappender); logger.info("Welcome"); logger.info("to"); logger.info("Rose India"); logger.info("Writer Appender"); logger.info("Example"); logger.info("‐‐‐‐‐‐‐‐‐‐‐"); } catch (Exception e){ System.out.println("Exception is ="+e.getMessage()); } } }

Output:

After compilation and execution of WriterAppenderExample.java will add the log events in

"Writer.html" file in the HTML format as since we have used HTMLLayout(). Output will look

like this.