Log4j Logging in Java



Overview:

Log4j is an open source project maintained by the Apache Foundation. It is available for many programming languages other than Java as well, such as C, C++, C#, and others.

In any application, maintaining the logs, and it's implementation is on and off required either by db log or logger file. Some time due to bad implementation of logger, application will slow down. But if there is any failure even though in live application, We can easily trace it out while enabling the debugging.

Hardware/Software requirement:
JDK (using 1.7)
Eclipse or any editor.
log4j-1.2.17.jar
Operating System

There are three main concepts in Log4j: loggers, appenders, and layouts. Loggers are objects that wait for an event to happen and put out a message then. Whether a certain event really triggers a certain logger or not depends on that event's importance, compared to the logger's importance threshold. If the event's importance (called priority or log level in Log4j) is equal to or higher than the logger's log level threshold, that logger prints out a message. If the event's log level is lower than the logger's log level, the logger is not triggered.

Log4j differentiates five such log levels (in ascending order): DEBUG, INFO, WARN, ERROR, FATAL, NONE. A logger set to NONE will never be triggered.

tutorialbyexample.com, Log4j, java, fatel, error, info, log














In above image, a logger set to the DEBUG level will report any event that is passed to it, a logger set to FATAL will only report events of level FATAL.

Example:

1. Create the java project in eclipse:
    File > New > Java Project > Next > Project Name: log4jbycorejava > Next > Finished.
2. Right click on the src > New > class >Package : log4jbycorejava > name: Log4JCoreJavaSample >         Finished

3. Log4JCoreJavaSample .java
package log4jbycorejava;

import org.apache.log4j.Logger;

public class Log4JCoreJavaSample {
final static Logger logger = Logger.getLogger(Log4JCoreJavaSample.class);
public void callMeInAppInfo(String parameter) {
if (logger.isInfoEnabled()) {
logger.info("This is info : " + parameter);
}
}
public void callMeInAppWarn(String parameter) {
if (logger.isWarnEnabled()) {
logger.warn("This is warn : " + parameter);
}
}
public void callMeInAppDebug(String parameter) {
if (logger.isDebugEnabled()) {
logger.debug("This is Debug : " + parameter);
}
}
public void callMeInAppError(String parameter) {
if (logger.isErrorEnabled()) {
logger.error("This is error : " + parameter);
}
}
public void callMeInAppFatal(String parameter) {
if (logger.isFatalEnabled()) {
logger.fatal("This is fatal : " + parameter);
}
}
}

4. Right click on the src > New > class > Package : log4jbycorejava > name: MainApp > Finished
MainApp.java
package log4jbycorejava;

public class MainApp {
public static void main(String[] args) {
Log4JCoreJavaSample objLog4JCoreJavaSample = new Log4JCoreJavaSample();
objLog4JCoreJavaSample.callMeInAppInfo("Log4JCoreJavaSample by Info");
objLog4JCoreJavaSample.callMeInAppWarn("Log4JCoreJavaSample by Warn");
objLog4JCoreJavaSample.callMeInAppDebug("Log4JCoreJavaSample by Debug");
objLog4JCoreJavaSample.callMeInAppError("Log4JCoreJavaSample by Error");
objLog4JCoreJavaSample.callMeInAppFatal("Log4JCoreJavaSample by Fatel");
}
}

5. Right click on the src > New > File > File name: log4j.properties > Finished.
log4j.properties
###### LOG4J SETTINGS ####################################################
# Log4J Settings
###########################################################################
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=c:\\log4j-application.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=2
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

6. Add the log4j-x.x.x.jar file in project. Download from http://logging.apache.org

7. Directory structure look like below

















8. Run it. Right Click on the MainApp.java > Run As > Java Application.
9. Console output and file creation in c:\log4j-application
2015-02-06 16:05:57 INFO  Log4JCoreJavaSample:12 - This is info : Log4JCoreJavaSample by Info
2015-02-06 16:05:57 WARN  Log4JCoreJavaSample:20 - This is warn : Log4JCoreJavaSample by Warn
2015-02-06 16:05:57 DEBUG Log4JCoreJavaSample:28 - This is Debug : Log4JCoreJavaSample by Debug
2015-02-06 16:05:57 ERROR Log4JCoreJavaSample:36 - This is error : Log4JCoreJavaSample by Error
2015-02-06 16:05:57 FATAL Log4JCoreJavaSample:44 - This is fatal : Log4JCoreJavaSample by Fatel

10. Errors: Chang the value of
log4j.appender.file.File=c:\\log4j-application.log
to
log4j.appender.file.File=d:\\log4j-application.log

11.  Run it for error. Right Click on the MainApp.java > Run As > Java Application.
Error: No file will created in d: as drive not exist in my system.

log4j:ERROR setFile(null,true) call failed.
java.io.FileNotFoundException: d:\log4j-application.log (The device is not ready)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:136)
at org.apache.log4j.FileAppender.setFile(FileAppender.java:294)
at org.apache.log4j.RollingFileAppender.setFile(RollingFileAppender.java:207)
at org.apache.log4j.FileAppender.activateOptions(FileAppender.java:165)
at org.apache.log4j.config.PropertySetter.activate(PropertySetter.java:307)
at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:172)
at org.apache.log4j.config.PropertySetter.setProperties(PropertySetter.java:104)
at org.apache.log4j.PropertyConfigurator.parseAppender(PropertyConfigurator.java:842)
at org.apache.log4j.PropertyConfigurator.parseCategory(PropertyConfigurator.java:768)
at org.apache.log4j.PropertyConfigurator.configureRootCategory(PropertyConfigurator.java:648)
at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:514)
at org.apache.log4j.PropertyConfigurator.doConfigure(PropertyConfigurator.java:580)
at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:526)
at org.apache.log4j.LogManager.<clinit>(LogManager.java:127)
at org.apache.log4j.Logger.getLogger(Logger.java:117)
at log4jbycorejava.Log4JCoreJavaSample.<clinit>(Log4JCoreJavaSample.java:7)
at log4jbycorejava.MainApp.main(MainApp.java:5)
2015-02-06 16:11:41 INFO  Log4JCoreJavaSample:12 - This is info : Log4JCoreJavaSample by Info
2015-02-06 16:11:41 WARN  Log4JCoreJavaSample:20 - This is warn : Log4JCoreJavaSample by Warn
2015-02-06 16:11:41 DEBUG Log4JCoreJavaSample:28 - This is Debug : Log4JCoreJavaSample by Debug
2015-02-06 16:11:41 ERROR Log4JCoreJavaSample:36 - This is error : Log4JCoreJavaSample by Error
2015-02-06 16:11:41 FATAL Log4JCoreJavaSample:44 - This is fatal : Log4JCoreJavaSample by Fatel


How to change the color of console?
We can achieved by ANSIConsoleAppender and adding value of log4j.appender.CONSOLE.warnColor=34;2

Must watch both videos:





Just put your point of view if any.
Don't be over smart in front of your near and dear, you are by born so no need to show them!


6 comments:

  1. You have my day with such nice explanation, explain more about real examples....

    ReplyDelete
  2. Good tutorial of log4j...keep posting

    ReplyDelete
    Replies
    1. Thanks for your feedback, you can watch latest video on log4j .. https://youtu.be/3r2LzaJ4pho however will post more example

      Delete
  3. I had done the same thing but i was getting an error please help me in that case

    ReplyDelete