Log4j working Selenium

Log4j is a replacement of System.out.println statements in java.
We will understand why people uses logs in a program.

In Industry whenever we write any method we log below statements like below snap. This helps in debugging of any issues in future.

test case log example

Now this will be printed with time like Wed Aug 30 18:07:33 IST 2017
This is just to know which test case started at what time.



  • Now we saw these statements cannot be controlled. I mean we cannot stop them from printing, once written they will be printed.

  • Formatting of statement cannot be done like first date and time then method name then logging statement. If we want to do we need to write again and again.

  • This can be easily solved by ‘log4j’.

  • We can have format defined for logs in log4j at centralize place.

  • We can disable or enable some category of logs.

  • Logs can be divided as per there category, explained later.


Try understanding log4j how it is working?

  • In industry we have categories defined for various logging statement.

    • error()
    • warn()
    • info()
    • debug()
    • fatal()
  • Now every company has their own standards to follows. If we have informative things to log then use info.

  • If we feel something will be needed to debug in future then use debug.

  • If we are using catch block then go for fatal similarly we need to thing where to use what.

  • One file is responsible for formatting of a logs and enabling and disabling of above levels is log4j.properties or log4j.xml

  • Printing to various sources can be done through log4j whereas System.out.println prints only on console.

  • Appenders and layouts are used for printing to console or sql or to file.

  • Log4j has three main components (loggers, Appenders and layouts) which works together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

Here in this example we will create one log file for every package.

  • Create project structure like below.

  • log4j structure

  • Code will be as below.

  • log4j example

    log4j example

    log4j example

  • Run SampleAdmin’s main method and then refresh the project where you will see below shown structure.

  • log4j structure

  • Now see both files and see logging statements.

  • log4j log files

  • Observe output.

We will be writing here one very simple program for log4j. Read property file and selenium code for the same.

  • Now go ahead with different types of Appenders and you will get to learn many more things. Try changing the format of output. Learn every line of the properties file. Try enabling and disabling every type of level like info or debug.

  • This concept is very good to know as as these concepts prove to be useful during an interview and looks good on your profile/resume.