Thursday, September 19, 2019

Post#74.Log4j with Selenium

Log4J

Log4j is framework which helps the java user to record the messages (logs) during the execution time. Logs are nothing but the detailed execution steps
Log4j write all the messages into files, files could be in many formats like text file, logfile, html file. Users have to configure the log4j before using it.

Advantages of Logging in Selenium Scripts:

·       Grants a complete understanding of test suites execution
·       Log messages can be stored in external files for post-execution scrutiny
·       Logs are an exceptional assistant in debugging the program execution issues and failures
·       Logs can also be reviewed to ascertain the application’s health by the stakeholders

Components of log4j:

  • Logger
  • Appender
  • Layout

Logger Object

Logger captures the log messages generated by the framework, and it passes the logs to appends. Logger decides where to send the information like whether to file or to console. Loggers also decide what priority level to be captured.

Layout Object

The Layout component defines the format in which the log statements are written to the log destination by appender, like html or .log so on. 
Layout objects play an important role in publishing logging information in a way that is human-readable and reusable.
There are diffrent kind of layout are present
  • SimpleLayout : it presents the log level - log messages format
  • PatternLayout : formats the output based on a conversion pattern specified, or if no conversuon specified, it takes the default conversion pattern
  • HTMLLayout : present the log messages as HTML table to the user.
  • XMLLayout : It provides the logs in the format of XMl.

Appender Object

Appenders writes the log messages decided by the logger into file or to database. Appenders delegates the message to the formatter. There diffreent kind of appenders.
  • FileAppender : It appends the message to a file.
  • RollingFileAppender : It also appends the messages to the file with filesize limit, when the file reachs the size limit automatically it creates another file and adds the messages.
  • DailyRollingFileAppender : It is Similar to Rolling File Appender, but it creates the files based on the given frequency.
  • ConsoleAppender : This appends to the console of the system.
  • SMTPAppender : This sends mail to the specific mail when an priority level occurs, example : sends mail when FATAL error occurs.
  • SysyLogAppender : Appends to a remote syslog domain.
Implementation
Logging using log4j can be implemented and configured in namely two ways:
1.      Programmatically via script
2.      Manually via Configuration files (using log4j.properties File or Xml file)

Implementation via script:

package pack2;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

public class Log4jJava {

    public static void main(String[] args) {
        // creates pattern layout
        PatternLayout layout = new PatternLayout();
        String conversionPattern = "[%p] %d %c %M - %m%n";
        layout.setConversionPattern(conversionPattern);

        // creates daily rolling file appender
        DailyRollingFileAppender rollingAppender = new DailyRollingFileAppender();
        rollingAppender.setFile("app.log");
        rollingAppender.setDatePattern("'.'yyyy-MM-dd");
        rollingAppender.setLayout(layout);
        rollingAppender.activateOptions();

        // configures the root logger
        Logger rootLogger = Logger.getRootLogger();
        rootLogger.addAppender(rollingAppender);

        // creates a custom logger and log messages
        Logger logger = Logger.getLogger(Log4jJavaClass.class);

        logger.debug("this is a debug log message");
        logger.info("this is a information log message");
        logger.warn("this is a warning log message");

    }
}
Output:
2018-10-11 15:43:33 DEBUG Log4jJavaClass:31 - this is a debug log message
2018-10-11 15:43:33 INFO  Log4jJavaClass:32 - this is a information log message
2018-10-11 15:43:33 WARN  Log4jJavaClass:33 - this is a warning log message

PatternLayout

Manually via Configuration files (using log4j.properties File)

Step-1:
Configure log4j.properties file (You can refer below link to configure log4j.properties file)
The log4j.properties file will be as below.
log4j.rootLogger=info, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
#Set Your applog.log file's path bellow.
log4j.appender.R.File=LogFiles//applog.log
log4j.appender.R.MaxFileSize=500KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.Append=false
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss,SSS} - %c - %p - %m%n

Note: the output log file (applog.log) will be generated under LogFiles folder.
Step-2:
Configure Java Class.
package pack2;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jTest {
              public static Logger log=null;
              public static void main(String[] args) {
String log4jConfigFile = System.getProperty("user.dir")+"//log4j.properties";
        PropertyConfigurator.configure(log4jConfigFile);
        log = Logger.getLogger("rootLogger");
        log.info("this is a information log message");
        log.error("this is a debug log message");
        log.warn("this is a warning log message");
              }

}
Execute your test case and refresh your Project. Verify that one applog file has been created under LogFiles Folder.
If you will open the applog file you can see the log message has been generated as below.
19 Oct 2018 22:37:46,121 - rootLogger - INFO - this is a information log message
19 Oct 2018 22:37:46,126 - rootLogger - ERROR - this is a debug log message
19 Oct 2018 22:37:46,126 - rootLogger - WARN - this is a warning log message

Manually via Configuration files (using log4j.xml File)

We can also configure the log4j logging system with xml configuration file. Please follow below steps to configure the log4j with xml.

Step#1: Save the below code as log4j.xml file.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
      <!-- Pattern to output the caller's file name and line number -->
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}-%x-%-5p-%-10c-%t:%m%n"/>
    </layout>
  </appender>
  <appender name="R" class="org.apache.log4j.RollingFileAppender">
    <param name="file" value="log/logFile.log"/>
    <param name="MaxFileSize" value="100KB"/>
    <!-- Keep one backup file -->
    <param name="MaxBackupIndex" value="1"/>
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss}-%x-%-5p-%-10c-%t:%m%n"/>
    </layout>
  </appender>
  <root>
    <priority value ="debug" />
    <appender-ref ref="stdout" />
    <appender-ref ref="R" />
  </root>
</log4j:configuration>

Step#2: Integrate log4j.xml file with java code

Program for XML integration with log4j

package logging;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class Log4jEx {
              static Logger log = Logger.getLogger(Log4jEx.class);

              public static void main(String[] args)
              {
                             //DOMConfigurator is used to configure logger from xml configuration file
                             DOMConfigurator.configure("D:\\log4j1.xml");

                             //Log to file
                             log.fatal("Log4j XML configuration is successful !!");
              }
}

Output:


HTML Logging in Log4J

This layout outputs events in a HTML table. Refer the below steps to configure HTML logging in log4j.
Step-1:
Configure log4j.properties file.
The log4j.properties file will be as below.
log4j.rootLogger=info, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
#Set Your applog.log file's path bellow.
log4j.appender.R.File=LogFiles//applog.log
log4j.appender.R.MaxFileSize=500KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.Append=false

log4j.appender.R.layout=org.apache.log4j.PatternLayout
# Define the html layout for file appender
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=HTML log
log4j.appender.HTML.layout.LocationInfo=true
log4j.appender.HTML.Threshold=DEBUG


Step#2: Integrate log4j.properties file with java code
package logging;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jHTML {

              public static Logger log=null;
              public static void main(String[] args) throws InterruptedException {
String log4jConfigFile = System.getProperty("user.dir")+"\\src\\test\\resources\\log4j-html.properties";
        PropertyConfigurator.configure(log4jConfigFile);
        log = Logger.getLogger("rootLogger");
        log.info("this is a information log message");
        Thread.sleep(3000);
        log.error("this is a debug log message");
        Thread.sleep(2000);
        log.warn("this is a warning log message");
              }

}
Output: 

No comments:

Post a Comment