Ads 468x60px

Tuesday, July 24, 2012

Java: Apache Log4j

This will help you to make logs of your programs. Please include log4j.jar to run this code. you can download this from following link:

// The logger class
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.FileAppender;

public class ServiceLog {

private static Logger logger = null;
private static String pattern = "";
private static String logfile = "ServiceLogInformation";

public static void setLog(Logger loging) {

logger = loging;
pattern += "Milliseconds since program start: %r %n";
pattern += "Classname of caller: %C %n";
pattern += "Date in ISO8601 format: %d{ISO8601} %n";
pattern += "Location of log event: %l %n";
pattern += "Message: %m %n %n";

PatternLayout layout = new PatternLayout(pattern);
FileAppender appender = null;
try {
appender = new FileAppender(layout, logfile, true);
} catch (IOException e) {


// This class will use above class for logging
import org.apache.log4j.Logger;

public class Service {
       private static Logger logger = Logger.getLogger(Service.class);

public static void main(String[] args) {

try {
                           // do something
                  catch (Exception ex) {
                               logger.setLevel((Level) Level.ERROR);

No comments:

Post a Comment