Tuesday 13 May 2014

Using Log4j on Eclipse

Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License.


What do you require to use log4j in eclipse project : apache-logging-log4j.jar (http://logging.apache.org/log4j/1.2/download.html )

You will get zip file for the jar. Unzip and save tge jar file in a directory and import the jar file in project.
Right click on the project and click properties.
Now click on java build path and click on Add External jars.
Add the external jar for the log4j logging.
Now you wizard should looks like this.(must have apache-logging-log4j.jar entry)





Java Files
1. StudentActivities.java

package firstLog;

import org.apache.log4j.Logger;

public class StudentActivities
{
static Logger log = Logger.getLogger(StudentActivities.class);
public void takeadmission()
{
log.info("Student has taken admission");
firstYear();
}
private void firstYear()
{
log.info("student in first year");
secondYear();
}

private void secondYear()
{
log.info("student ins second year");
thirdYear();
}

private void thirdYear()
{
log.info("student in third year");
fourthYear();
}

private void fourthYear()
{
log.info("student in fourth year");
professional();
}

private void professional()
{
log.info("Now he is a professional");
}
}

2. Run.java

// Using JUnit to run the program (can be replaced by a class with main method)

package firstLog;

import org.junit.Test;

public class Run
{
@Test
public void testStudentActivities()
{
StudentActivities studentActivities = new StudentActivities(); 
studentActivities.takeadmission();
}

}


3. log4j.properties (should be in project's src folder)


# This sets the global logging level and specifies the appenders
log4j.rootLogger=INFO, theConsoleAppender, FILE

# settings for the console appender
log4j.appender.theConsoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.theConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.theConsoleAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=logs/log.txt
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

log4j.appender.FILE.Append=true

Now project explorer should looks like this:



Run the program and you can see the logs in /logs/log.txt

Hope this helps you :)