How to Configure Log4j in your project (Using Log4j.xml file)?

 Configure Log4j in your project with the help of Log4j.xml file
To start with using logger, below steps explain, how can we use Log4j for logging the required messages which can be used later on, might be for debugging propose or is informative
Step1: Download Log4j from below link (Official site)
Log4j is a logging library used in java development. Firstly download Log4j.jar from its official site (Apache)
Step2: Add Log4j.jar to project library
We need to add this jar file in to the build path. To do this, right click on the project -> Build path -> Configure Build path -> Libraries tab -> Add external Jar -> Select Log4j.jar
Now Log4j is added in to your library and we are good use it.
Step3: Create Log4j.xml file (Note: Create Under src folder)
In order to configure Log4j in project, we need to specify various parameters in xml file.
The parameters we need to provide are logger, appenders, layout etc.
These parameters need to create in xml file.
To do this, right click on src folder -> New -> Other -> File -> give the name as “Log4j.xml”.
Now we can see the blank xml file.
Add the blow lines of code in to the xml file. Save the file.
(To learn about how logging can be achieved using log4j.properties file, click here– )
To write this xml file, one should know about 3 Main components of Log4j, different logging levels in Log4j.
Refer the blow links – 

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration debug="true"

xmlns:log4j='http://jakarta.apache.org/log4j/'>



<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/>

</layout>

</appender>



<appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">

<param name="append" value="false"/>

<param name="file" value="out/learning.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p [%c{1}] %m%n"/>

</layout>

</appender>



<root>

<level value="INFO"/>

<appender-ref ref="consoleAppender"/>

<appender-ref ref="fileAppender"/>

</root>



</log4j:configuration>

If you want to provide the max size, we can add below statement as param to RollingFileAppender.

<param name="maxFileSize" value="1MB" />
We can define ‘MaxBackupIndex’ option which determines the number of previously rolled files to preserve. MaxBackUp takes only a positive integer value. MaxBackUp value will be set to 1 by default. If we set it to zero, then no roll over occurs and the log file will be simply truncated when it reaches the MaxFileSize.

<param name="MaxBackupIndex" value="2"/>
Step4: Create Sample class where we will use Logger
Once Log4j.properties file is created, all is set to write log in your java program.
To achieve this, create sample class.
To define Logger class, use blow syntax
                        

Logger log = Logger.getLogger("your_class_name")
Import suitable respective jar.

Below sample code shows how can we log the information for various logging level.

Sample Program:

package com.aayushCorp.appData.tests;

import org.apache.log4j.Logger;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;


public class LoggerExampleTest {


public static void main(String[] args) {



Logger log = Logger.getLogger("LoggerExampleTest");

WebDriver driver = new FirefoxDriver();

driver.navigate().to("https://www.google.co.in");


log.info("This is Info message - Launched Google");

log.debug("This is debug message");

log.error("This is error message");

log.fatal("This is fatal mesage");

log.trace("This is trace message");



driver.close();

}


}

Run the program, you will see below output.

Output:

INFO [main] (LoggerExampleTest.java:16)- This is Info message - Launched Google

DEBUG [main] (LoggerExampleTest.java:17)- This is debug message

ERROR [main] (LoggerExampleTest.java:18)- This is error message

FATAL [main] (LoggerExampleTest.java:19)- This is fatal mesage

TRACE [main] (LoggerExampleTest.java:20)- This is trace message

Based on Log4j.xml file, log messages will be stored in .log file (text file) at the defined path on xml file.

Below screenshot shows the folder location and respective log file.
Hope this helps.
 Related Topic: 

How to Configure Log4j in your project (Using Log4j.properties file) ?

Configure Log4j in your project with the help of Log4j.properties file – 

To start with using logger, below steps explain, how can we use Log4j for logging the required messages which can be used later on, might be for debugging propose or is informative

Step1: Download Log4j from below link (Official site)
Log4j is a logging library used in java development. Firstly download Log4j.jar from its official site (Apache)   http://logging.apache.org/log4j/1.2/download.html
Step2: Add Log4j.jar to project library
We need to add this jar file in to the build path. To do this, right click on the project -> Build path -> Configure Build path -> Libraries tab -> Add external Jar -> Select Log4j.jar

Now Log4j is added in to your library and we are good use it.
Step3: Create Log4j.properties file (Note: Create Under src folder)
In order to configure Log4j in project, we need to specify various parameters in properties file.
The parameters we need to provide are logger, appenders, layout etc.
These parameters need to create in properties file.
To do this, right click on src folder -> New -> Other -> File -> give the name as “Log4j.properties”.

Now we can see the blank text file.
Add the blow lines of code in to the properties file. Save the file.
To write this properties file, one should know about 3 Main components of Log4j, different logging levels in Log4j.

Refer the blow links –
Main Components of Log4j

Different Logging levels in Log4j

// Here we have defined root logger

log4j.rootLogger=ALL,CONSOLE,R


// Here we define the appender

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.R=org.apache.log4j.RollingFileAppender

#log4j.appender.TTCC=org.apache.log4j.RollingFileAppender

#log4j.appender.HTML=org.apache.log4j.FileAppender


// Here we define log file location

log4j.appender.R.File=./log/testlog.log

#log4j.appender.TTCC.File=./log/testlog1.log

#log4j.appender.HTML.File=./log/application.html


// Here we define the layout and pattern

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern= %5p [%t] (%F:%L)- %m%n

log4j.appender.R.layout=org.apache.log4j.PatternLayout

log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n

#log4j.appender.TTCC.layout=org.apache.log4j.TTCCLayout

#log4j.appender.TTCC.layout.DateFormat=ISO8601

#log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout

#log4j.appender.HTML.layout.Title=Application log

#log4j.appender.HTML.layout.LocationInfo=true

Step4: Create Sample class where we will use Logger

Once Log4j.properties file is created, all is set to write log in your java program.
To achieve this, create sample class.
To define Logger class, use blow syntax
                                Logger log = Logger.getLogger(“your_class_name”);
Import suitable respective jar.
Below sample code shows how can we log the information for various logging level.
Sample Program:
package com.aayushCorp.appData.tests;

import org.apache.log4j.Logger;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class LoggerExampleTest {

 

                public static void main(String[] args) {

                               

                                Logger log = Logger.getLogger("LoggerExampleTest");

                                WebDriver driver = new FirefoxDriver();

                                driver.navigate().to("https://www.google.co.in");





                                log.info("This is Info message - Launched Google");

                                log.debug("This is debug message");

                                log.error("This is error message");

                                log.fatal("This is fatal mesage");

                                log.trace("This is trace message");

                               

                                driver.close();

                }

 

}
Run the program, you will see below output.
Output:
INFO [main] (LoggerExampleTest.java:16)- This is Info message - Launched Google

DEBUG [main] (LoggerExampleTest.java:17)- This is debug message

ERROR [main] (LoggerExampleTest.java:18)- This is error message

FATAL [main] (LoggerExampleTest.java:19)- This is fatal mesage

TRACE [main] (LoggerExampleTest.java:20)- This is trace message
Based on Log4j.properties file, log messages will be stored in .log file (text file) at the defined path on properties file.
Below screenshot shows the folder location and respective log file.
Hope this helps.

What are the different logging levels in Log4j ?

There are several logging levels that you can configure in your application.
Anybody who is using logging in java must be familiar with basic java logging level e.g. DEBUG, INFO, WARN and ERROR.
Those are FATAL, ERROR, WARN, TRACE, DEBUG, INFO OR ALL in Apache logging. Default logging level is INFO.
Logging levels are given below:
1. ALL: All levels including custom levels also.
2. DEBUG: The DEBUG Level is used to indicate events that are useful to debug an application. Handling method for DEBUG level is: debug().
3. INFO: It gives the information about the progress of application and its states. General tips, news information etc.
4. WARN: It gives warning for unexpected events. The WARN level is used to indicate potentially harmful situations. Handling method for WARN level is: warn().
5. ERROR: It provides the information about error events. The ERROR level shows errors messages that might not be serious enough and allow the application to continue. Handling method for ERROR level is: error().
6. FATAL: It provides the information about application abort. The Fatal level is used to indicate severe events that will may cause abortion of the application. Handling method for FATAL level is: fatal().
7. OFF: It turns off all the logging. It is opposite to the ALL level. OFF java logging level has the highest possible rank and is intended to turn off logging in Java.
Standard order of all logging levels:
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.
i.e. If logging level set to FATAL then only FATAL messages will be displayed, if logging level set to ERROR then ERROR and FATAL messages will be displayed and so on.
In the below example as we set the logging level to WARN so only WARN, ERROR and FATAL messages will be displayed. The DEBUG and INFO message will not display.
If you declare log level as debug in the configuration file, then all the other log messages will also be recorded.
If you declare log level as info in the configuration file, then info, warn, error and fatal log messages will be recorded.
If you declare log level as warn in the configuration file, then warn, error and fatal log messages will be recorded.
If you declare log level as error in the configuration file, then error and fatal log messages will be recorded.
If you declare log level as fatal in the configuration file, then only fatal log messages will be recorded.

How logging in Java affects performance?

Does Logging in java affects the performance of the application?    
    Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application’s runtime information.
    Logging does have its drawbacks also. It can slow down an application as it uses some CPU cycles and other resources (memory, etc). To answer these concerns, log4j is designed to be reliable, fast and extensible. Also, one should only log an error or something that must absolutely be logged. You can also log information helpful for debugging in the debug channel so it won’t affect production performance.
    Make sure you have a proper logging strategy. That means make sure you define what to log and have it separated into debug, trace, info, warning and error as well some others if you need them. Also make sure you give the ability to switch it on and off to enact performance/debugging as needed.
   Java logging severely affects performance of your application. Its quite common sense that more you log, more you perform file IO which slows down your application. That’s why choosing correct java logging level for every single message is quite important. Since having no java logging is not a choice you have to have logging in java application, what you can control is logging level and logging messages on that level. So always log DEBUG messages inside isDebugEnabled() block as shown in below example of debug mode in java.
 if(logger.isDebugEnabled()){
logger.debug("java logging level is DEBUG Enabled");
}

To improve performance:

>>  Change the ConversionPattern to use less expensive date/time formatting, and (more importantly) avoid ‘C’, ‘F’, ‘L’ and ‘M’ because they are particularly expensive.
>>   Change the logging Threshold to INFO or WARNING or ERROR to reduce the amount of logging,

>>   Put the Logger.debug(…) call inside an if statement that checks that debug logging is enabled. This   saves the cost of assembling the log message in cases where it won’t be needed;

>>  You can restrict junk logs like this. Set the root logger as INFO so that unnecessary debug logs won’t come and fill up your log file.
log4j.rootCategory=INFO, A1

>>   If you want specific class or package to give out DEBUG logs you can do it like this.

log4j.logger.org.hibernate.event.def.DefaultLoadEventListener=DEBUG,A1

The above will print DEBUG level logs from the class DefaultLoadEventListener in your log file along with other INFO level logs.

Main Components of Log4j

What are different appenders that can configure in log4j?
There are 3 main components that are used to log messages based upon type and level.
These components help to log messages according to message type and priority. Also provide the formatting option.
These components are:
– loggers
– appenders
– layouts
Logger Object is responsible for storing the information which need to be logged
We need to create Logger Object in a class (one per class).
Example:      static Logger log = Logger.getLogger(“your_class_name”);
Appender Objectis used to define the destination like file system, console, database, mail server etc. where user wants to save the log messages.
There are various appenders –
FileAppender –> used to write into a file. Files Appender is used to log the information into our custom name files. when we are configuring this appender, we can specify the file name
ConsoleAppender –> used to write into console. if we use this as appenders in your application, log4j logs the information in the console or command prompt window that is started with startup script.
JDBCAppender –> used to write in database
SMTPAppender –> used to send the log over mail
Again, in FileAppender we have 2 more
RollingFileAppenderwhich Rotates based on a maximum file size.
RollingFileAppender extends FileAppender to backup the log files when they reach a certain size. The log4j extras companion includes alternatives which should be considered for new deployments and which are discussed in the documentation for org.apache.log4j.rolling.RollingFileAppender.
It has two important menthods –
setMaximumFileSize – Set the maximum size that the output file is allowed to reach before being rolled over to backup files.
setMaxBackupIndex – Set the maximum number of backup files to keep around.
DailyRollingFileAppender which Rotates based on dateFormat.
DailyRollingFileAppender extends FileAppender so that the underlying file is rolled over at a user chosen frequency. DailyRollingFileAppender has been observed to exhibit synchronization issues and data loss.
Layout Object is responsible for layout and formating of the logging information to the desired format.
We have different type of layout classes in log4j
    SimpleLayout
    PatternLayout
    HTMLLayout
    XMLLayout

Why Log4j is better than System.Out.Println? (What is difference between log4j and common loggings?)

   Log4j is a logging framework, it is used as standard logger nowadays compared to System.out.println.
       Log4j has certainly various advantages over System.out.println,  firstly being checking the output the system.out.println outputs to standard output which is mostly a console window whereas the output from Log4j can be to the console or email server, database table or a log file.
Additionally, in Log4j different levels of logging can be set such as TRACE, DEBUG, INFO, WARN, ERROR and FATAL. If a log level is set messages will be logged for that level and level below it.
   Log4j allows logging on class-by-class basis i.e., each class can be covered whereas System.out.println can be controlled at application level. Through Log4j we can turn on or off the logging at runtime by changing the configuration file.
The Main Reasons why Log4j is better than system.out.println() –
•  There are various levels of logging i.e all, trace, debug, info, warn, error and fatal. You can log at whatever you want in production as compared to println that can only print logs on the console. In log4j you can change the granularity of logging based on your requirement.
•  Logging can be controlled at runtime using the configuration file as compared to println that requires a compilation and code deployment.
•  You can target logs as per your convenience, you can keep them in log files. Later you can archive these log files where as println prints out on console and you may get “Out of memory” on buffers.
•  Loggers are usually optimized for speed.
•  Logging support internationalization
•  Log4j allows you to print the logs at multiple locations. Not only that it allows you to print out the logs asynchronously. log4j allows you to define your own writing strategy.
•  Using log4j you can specify the output format of logs. You can define your own conversion pattern. It allows you to include all the required information you want in your logs in the required pattern.

Hope this helps —

 Why do we need logging in Java / Selenium?

Log4j is a logging framework, it is used as standard logger nowadays, as compared to System.out.println.
Log4j has certainly various advantages over System.out.println firstly being checking the output, the outputs to standard output which is mostly a console window whereas the output from Log4j can be to the console or email server, database table or a log file.
Additionally, in Log4j different levels of logging can be set such as TRACE, DEBUG, INFO, WARN, ERROR and FATAL. If a log level is set messages will be logged for that level and level below it.
Log4j allows logging on class-by-class basis i.e., each class can be covered whereas System.out.println can be controlled at application level. Though Log4j we can turn on or off the logging at runtime by changing the configuration file.
         Everybody who starts java starts with System.out.println() for printing message in java console. But this is not at all powerful as compared to advanced Java logging API like log4j and java.util.logging. If you are writing a java application server then only way to know what your server is doing is by seeing log file of your server. 
        suppose you don’t write anything in your java log file then nobody knows what your sever is doing, it becomes increasingly important if your application is connected to upstream and downstream like in many stock trading systems or electronic trading system and get input from upstream, transforms and normalize it and send down to downstream. In case of any issue without java logs you won’t be able to figure out what went wrong. That’s why logging in java is most important while writing any Java server application. Logging in Java is not by choice it’s must to understand.

Following are the Pros and Cons of Logging −

>  Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application’s runtime information.
>  Logging does have its drawbacks also. It can slow down an application. If too verbose, it can cause scrolling blindness. To alleviate these concerns, log4j is designed to be reliable, fast and extensible.

> Since logging is rarely the main focus of an application, the log4j API strives to be simple to understand and to use