Log4j Index: What Is Log4j, Why Log4j Came Into Picture
Log4j Index: What Is Log4j, Why Log4j Came Into Picture
What Is Log4j, Why Log4j Came Into Picture What Are The Main Components Of Log4J Log4j Hello World Program How To Create Log4j.properties File Example On Log4j.properties File With FileAppender & SimpleLayout Log4j Example On Using FileAppender And ConsoleAppender Simultaneously
Logger
Logger is a class, in org.apache.log4j.* We need to create Logger object one per java class
This component enables Log4j in our java class Logger methods are used to generate log statements in a java class instead of sopls So in order to get an object of Logger class, we need to call a static factory method [ factory method will gives an object as return type ] We must create Logger object right after our class name, i will show you
Example
1public class Client { 2 3 static Logger l = Logger.getLogger(Client.class.getName()); 4 public static void main(String[] args) { 5 // Our logic will goes here 6 } 7 } 8 Logger object has some methods, actually we used to print the status of our application by using these methods only We have totally 5 methods in Logger class
As a programmer its our responsibility to know where we need to use what method, did you observe there ? method names are different right, but all are same
Priority Order
debug < info < warn < error < fatal I mean, fatal is the highest error like some database down/closed
Remember: Friends dont confuse by seeing all these 5 methods all are same, for example if our application is about 100 lines and we have JDBC related code in some 45th line or some where there we used to write fatal() method. All it could be is just for human identification purpose names are different, else these 5 methods will print one text message only You will get more clarity once you saw the first program on log4j.
Appender
Appender job is to write the messages into the external file or database or smtp
Logger classes generates some statements under different levels right, this Appender takes these log statements and stores in some files or database Appender is an interface
FileAppender [ writing into a file ] ConsoleAppender [ Writing into console ] JDBCAppender [ For Databases ] SMTPAppender [ Mails ] SocketAppender [ For remote storage ] SocketHubAppender SyslogAppendersends TelnetAppender
RollingFileAppender DailyRollingFileAppender
For now just remember, i will explain while executing the program
Layout
This component specifies the format in which the log statements are written into the destination repository by the appender We have different type of layout classes in log4j
For working with log4j, we must set log4j.jar in our class path
Files Required
Client.java my.txt [ We will let the appender to write into this file ]
public class Client { static Logger l = Logger.getLogger(Client.class.getName()); public static void main(String[] args) { Layout l1 = new SimpleLayout(); Appender a; //Appender a = new ConsoleAppender(l1); try { a = new FileAppender(l1,"my.txt", false); // 3rd parameter is true by default // true = Appends the data into my.txt // false = delete previous data and re-write l.addAppender(a); } catch(Exception e) {} l.fatal("This is the error message.."); System.out.println("Your logic executed successfully....");
} }
my.txt
FATAL This is the error message..
Explanation
First step is to create one Logger class object [ see line number 9 ] Second step is to create Layout object [ see line number 13 ] Once Layout is ready, our next step is to create Appender [ see line number 18 ] In appender i have passed 3 parameters like.. first parameter is object of layout because, appender will write the error messages based on the layout we selected, then 2nd parameter is file name with extension [ in this file only appender will writes the messages ], then 3rd parameter is by default true, means appender will appends the error messages, if we give false then appender will clears the previous data in my.txt file and write newly
Hey see, i have used FileAppender, but if i would like to change my appender choice to ConsoleAppender, then again we must open this java file then modifications and recompile bla bla, so to avoid this we can use one .properties file, will see this in the next session.
log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,LOGFILE log4j.appender.CONSOLE= log4j.appender.CONSOLE.layout= log4j.appender.CONSOLE.layout.ConversionPattern= log4j.appender.LOGFILE= log4j.appender.LOGFILE.File= log4j.appender.LOGFILE.MaxFileSize= log4j.appender.LOGFILE.layout= log4j.appender.LOGFILE.layout.ConversionPattern=
Files Required
Client.java log4j.properties my.txt [ We will let the appender to write into this file ]
6 7 8 9 1 0 public static void main(String[] args) { 1 1 l.debug("This is debug message"); 1 l.info("This is info message"); 2 l.warn("This is warn message"); l.fatal("This is fatal message"); 1 l.error("This is error message"); 3 1 System.out.println("Your logic executed successfully...."); 4 1 } 5 } 1 6 1 7 1 8 Once we run this client program, my.txt will contains.
log4j.properties
log4j.rootLogger = DEBUG,abc log4j.appender.abc = org.apache.log4j.FileAppender log4j.appender.abc.file = my.txt log4j.appender.abc.layout = org.apache.log4j.SimpleLayout
my.txt
DEBUG This is debug message INFO This is info message WARN This is warn message FATAL This is fatal message ERROR This is error message
Execution Flow
As our default properties file name is log4j.properties, we no need to import properties file explicitly into Client.java, by default our java class will verify for the properties file named log4j.properties. If we give the name other than log4j to the properties we have to import manually into our java class [ will see this later, like how to manually ] So once Logger object created at line number 5, our class will be able to know about the content in log4j.properties In log4j.properties the content always will be in key,value pairs only
Explanation
If we use .properties file, we no need to import any related classes into our java class log4j.rootLogger = DEBUG,abc > Here DEBUG means we are specifying the level from where log4j methods execution must start, see my.txt file it showing all messages right. But if we wrote log4j.rootLogger = WARN,abc then it will prints the messages in l.warn(), l.error(), l.fatal() and ignores l.debug(), l.info() I have used FileAppender as my Appender, so if we want to change my appender to ConsoleAppender, i will open log4j.properties file and do the modifications, so no need to touch our java classes, this is the main advantage of .properties file
Files Required
Client.java log4j.properties my.txt [ We will let the appender to write into this file ]
8 9 1 0 1 1 1 2 1 3 1 4 1 5 } 1 6 } 1 7 1 8 1 9
l.debug("This is debug message"); l.info("This is info message"); l.warn("This is warn message"); l.fatal("This is fatal message"); l.error("This is error message"); System.out.println("Your logic executed successfully....");
log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,LOGFILE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x %m%n log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender log4j.appender.LOGFILE.File=my.txt log4j.appender.LOGFILE.MaxFileSize=1kb log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=[%t] %-5p %c %d{dd/MM/yyyy HH:mm:ss} %m%n
my.txt
[main] DEBUG Client 27/02/2012 21:39:15 This is debug message [main] INFO Client 27/02/2012 21:39:15 This is info message [main] WARN Client 27/02/2012 21:39:15 This is warn message
[main] FATAL Client 27/02/2012 21:39:15 This is fatal message [main] ERROR Client 27/02/2012 21:39:15 This is error message
class Rupee implements Currency { @Override public String getSymbol() { return "Rs"; } } // Concrete SGD class Code class SGDDollar implements Currency { @Override public String getSymbol() { return "SGD"; } } // Concrete US Dollar code class USDollar implements Currency { @Override public String getSymbol() { return "USD"; } } // Factroy Class code class CurrencyFactory { public static Currency createCurrency (String country) { if (country. equalsIgnoreCase ("India")){ return new Rupee(); }else if(country. equalsIgnoreCase ("Singapore")){ return new SGDDollar(); }else if(country. equalsIgnoreCase ("US")){ return new USDollar(); } throw new IllegalArgumentException("No such currency"); } } // Factory client code public class Factory { public static void main(String args[]) { String country = args[0]; Currency rupee = CurrencyFactory.createCurrency(country); System.out.println(rupee.getSymbol()); } }
2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory. 3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side. 4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.
DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");
Creating Blank DOM Document Posted on: February 26, 2008 at 12:00 AM This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents.
This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.
DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");
The instance of the class DocumentBuilder is used to create a blank document. The newDocument() method of the class returns a blank DOM document.
Document doc = parser.newDocument(); Here is the full code of CreateBlankDocument.java import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CreateBlankDocument { public static void main(String[] args) {
System.out.println("Creating Balnk Document..."); try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder parser = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = parser.newDocument(); }catch(Exception e){ System.out.println(e.getMessage()); } System.out.println("Done..."); System.out.println("Exiting..."); } }
DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");
Creating Blank DOM Document Posted on: February 26, 2008 at 12:00 AM
This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents.
This tutorial shows you how to create blank DOM document. JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM parsers. Normally it is used to a DOM parser. Example is as follows:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); Document doc = parser.parse(myInputSource); //The parse function is used to parse existing xml document.
DocumentBuilderFactory uses the system property javax.xml.parsers.XmlDocumentParserFactory to find the class to load. So you can change the parser by calling:
System.setProperty("javax.xml.parsers.XmlDocumentParserFactory", "com.foo.myFactory");
The instance of the class DocumentBuilder is used to create a blank document. The newDocument() method of the class returns a blank DOM document.
Document doc = parser.newDocument(); Here is the full code of CreateBlankDocument.java import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; public class CreateBlankDocument { public static void main(String[] args) { System.out.println("Creating Balnk Document..."); try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder parser = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = parser.newDocument();
Printing the DOM Tree on console An finally we will print the DOM tree on the console with the following code: TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); Here is the full code of CreateDomXml.java
import org.w3c.dom.*; import import import import javax.xml.parsers.*; javax.xml.transform.*; javax.xml.transform.dom.DOMSource; javax.xml.transform.stream.StreamResult;
class CreateDomXml { public static void main(String[] args) { try{ //Create instance of DocumentBuilderFactory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //Get the DocumentBuilder DocumentBuilder docBuilder = factory.newDocumentBuilder(); //Create blank DOM Document Document doc = docBuilder.newDocument(); //create the root element Element root = doc.createElement("root"); //all it to the xml tree doc.appendChild(root); //create a comment Comment comment = doc.createComment("This is comment"); //add in the root element root.appendChild(comment); //create child element Element childElement = doc.createElement("Child"); //Add the atribute to the child childElement.setAttribute("attribute1","The value of Attribute 1"); root.appendChild(childElement); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); }catch(Exception e){ System.out.println(e.getMessage()); } } }
After reading this section, you will be able to retrieve a root element from the XML document. The JAXP (Java APIs for XML Processing) provides a common interface for creating and using xml files using the standard SAX, DOM and XSLTs. Here you will see the given example to use DOM interface. Description of program: You need a XML document (file). Both Java and the XML file are kept in the same directory. This program takes a XML file as a String at the console . If the given file exists then it parses the document using parse() method . Before parsing the XML document you need a DocumentBuilder object. For creating this first of all you create a DocumentBuilderFactory. After parsing the XML document you get the node element using getDocumentElement() method. To get the root element use the getNodeName() method.
Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Here is the Java File: GetRootNode.java
import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class GetRootNode{ public static void main(String[] args) { try{ BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter xml file name: "); String str = bf.readLine(); File file = new File(str); if (file.exists()){ DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = fact.newDocumentBuilder(); Document doc = builder.parse(str); Node node = doc.getDocumentElement(); String root = node.getNodeName(); System.out.println("Root Node: " + root); } else{ System.out.println("File not found!");
} } catch(Exception e){} }
Output of the program: C:\vinod\xml>javac GetRootNode.java C:\vinod\xml>java GetRootNode Enter xml file name: Employee-Detail.xml Root Node: Employee-Detail
To Count XML Element Posted on: June 4, 2007 at 12:00 AM In this section, you will learn to count the elements present in a XML file using DOM APIs.
In this section, you will learn to count the elements present in a XML file using DOM APIs. Description of program: This program helps to count the XML element. It takes a xml file (as a string ) at the console and checks its availability. It parses the xml document using the parse() method. After parsing the XML document it asks for element name which have to count. Create a NodeList and use the getElementByTagName() method. The getLength() method counts the occurrences of the specified element. If the asked element is not available( i.e.. the given element isn't found) it returns 0. Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail>
<Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> </Employee-Detail> Here is the Java File: DOMCountElement.java
import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*; public class DOMCountElement{ public static void main(String[] args) { try { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if (file.exists()){ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Create the builder and parse the file Document doc = factory.newDocumentBuilder().parse(xmlFile); System.out.print("Enter element name: "); String element = bf.readLine(); NodeList nodes = doc.getElementsByTagName(element); System.out.println("xml Document Contains " + nodes.getLength() + " elements."); } else{ System.out.print("File not found!");
java.io.*;
public class CreatXMLFile { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter number to add elements in your XML file: "); String str = bf.readLine(); int no = Integer.parseInt(str); System.out.print("Enter root: "); String root = bf.readLine(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElement(root); document.appendChild(rootElement); for (int i = 1; i <= no; i++){ System.out.print("Enter the element: "); String element = bf.readLine(); System.out.print("Enter the data: "); String data = bf.readLine(); Element em = document.createElement(element); em.appendChild(document.createTextNode(data)); rootElement.appendChild(em); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } }
Getting all XML Elements Posted on: June 8, 2007 at 12:00 AM In this section, you will learn to retrieve all elements of the XML file using the DOM APIs.
In this section, you will learn to retrieve all elements of the XML file using the DOM APIs. This APIs provides some constructors and methods which helps us to parse the XML file and retrieve all elements. Description of program: The following program helps you in getting all XML elements displayed on the console. This program asks for a xml file name and checks its availability. whether the given file exists or not in the same directory. So, you need a XML file (Employee-Detail.xml) that contains some elements. Program parses the xml file using the parse() method and creates a Document object Tree. DocumentBuilder object helps you to get features to parse the XML file. After parsing the XML file a NodeList is created using the getElementsByTagName().This NodeList object creates element. Elements name are retrieved using the getNodeName() method. Here is the XML File: Employee-Detail.xml <?xml version = "1.0" ?> <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Vinod </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit </Emp_Name> <Emp_E-mail> [email protected] </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-003 </Emp_Id> <Emp_Name> Deepak </Emp_Name>
public class DOMElements{ static public void main(String[] arg){ try { BufferedReader bf = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter XML File name: "); String xmlFile = bf.readLine(); File file = new File(xmlFile); if(file.exists()){ // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create a builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); // Get a list of all elements in the document NodeList list = doc.getElementsByTagName("*"); System.out.println("XML Elements: "); for (int i=0; i<list.getLength(); i++) { // Get element Element element = (Element)list.item(i); System.out.println(element.getNodeName()); } } else{ System.out.print("File not found!"); } } catch (Exception e) { System.exit(1); } } }
C:\vinod\xml>java DOMElements Enter XML File name: Employee-Detail.xml XML Elements: Employee-Detail Employee Emp_Id Emp_Name Emp_E-mail Employee Emp_Id Emp_Name Emp_E-mail Employee Emp_Id Emp_Name Emp_E-mail