log4j in Java

log4j is very popular logging framework in Java. You can specify the settings of the framework using either XML file or properties file. Key things to know about log4j framework are –
  • It can be used to send the log messages to multiple appenders like file, console etc
  • Various log level are OFF, FATAL, ERROR, WARN, INFO, DEBUG and TRACE.
  • If you set the Log level as WARN, then only higher level (FATAL and ERROR)log messages are logged.
  • It allows you to set the log level at root level as well as class level.
  • We can restrict the log level for each appender using threshold parameter.
Here is the sample log4j.properties file. We usually keep this file in resources directory of the Java project.
 
#We have specified the logging level as INFO and 2 appenders are set up
log4j.rootLogger=INFO, mystdoutappender, myfileappender

# Send log messages to file with name mylog4j.log
log4j.appender.myfileappender=org.apache.log4j.FileAppender
log4j.appender.myfileappender.File=mylog4j.log
log4j.appender.myfileappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myfileappender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Send log messages to console - Standard Output Stream
log4j.appender.mystdoutappender=org.apache.log4j.ConsoleAppender
log4j.appender.mystdoutappender.Target=System.out
log4j.appender.mystdoutappender.layout=org.apache.log4j.PatternLayout
log4j.appender.mystdoutappender.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Here is the sample class using logger.

import org.apache.log4j.Logger;
import org.junit.Test;

/**
 * Created by Sagar on 04-07-2016.
 */
public class LogTest {
        final static Logger logger = Logger.getLogger(LogTest.class);

        @Test
        public void test1(){
            //OFF, FATAL, ERROR, WARN, INFO, DEBUG and TRACE
            logger.fatal("Fatal message");
            logger.error("Dump error");
            logger.warn("Warning baby");
            logger.info("Hello - This is info");
            //Below messages will not be logged as we have set the log level as INFO
            logger.debug("Debug message");
            logger.trace("Trace message");
        }
}
Here is the output of above example.

2016-07-14 19:09:43 FATAL LogTest:13 – Fatal message
2016-07-14 19:09:43 ERROR LogTest:14 – Dump error
2016-07-14 19:09:43 WARN LogTest:15 – Warning baby
2016-07-14 19:09:43 INFO LogTest:16 – Hello – This is info

Process finished with exit code 0

Web development and Automation testing

solutions delivered!!