Friday, August 28, 2009

Writing Logs to a Console and File using Log4j

While doing application development it's require you to write logs into File or print logs into Console with expected Date/Time, ProgramName with line number and many more information.

  1. Download Apache Log4j.jar and add it to your classpath
  2. Create Instance of Logger
  3. Use debug,info,warn,error,fatal methods to log required information
Writing Application logs to file using Java and Log4j :

package com.anuj.application;
import org.apache.log4j.Logger;

public class ClientApplication {

    static Logger logger = Logger.getLogger(ClientApplication.class.getName());
    public static void main(String[] args) {

    System.out.println("Application started successfully");

    logger.debug("This is debug message");
    logger.info("This is info message");
    logger.warn("This is warn message");
    logger.fatal("This is fatal message");
    logger.error("This is error message");
    System.out.println("Application end successfully");
     }
}
log4j.properties :
log4j.rootLogger=DEBUG,LOGFILE

log4j.appender.LOGFILE=org.apache.log4j.RollingFileAppender
log4j.appender.LOGFILE.File=application.log
log4j.appender.LOGFILE.MaxFileSize=10MB
log4j.appender.LOGHANDLE.MaxBackupIndex=10
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=[%t] %-5p %c %d{dd/MM/yyyy HH\:mm\:ss} - %m%n 
 
If your application requires to use Console Appender then you can use add ConsoleAppender in you application log4j.properties.

1. Define CONSOLE as rootLogger
2. Add Following lined into lo4j.properties
log4j.rootLogger=DEBUG,LOGFILE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{dd/MM/yyyy HH\:mm\:ss} [%t] %-5p %c{1} (%t\:%L) - %m%n 

Console Output :
Application started successfully
15/12/2012 23:28:46 [main] DEBUG ClientApplication (main:13) - This is debug message
15/12/2012 23:28:46 [main] INFO  ClientApplication (main:14) - This is info message
15/12/2012 23:28:46 [main] WARN  ClientApplication (main:15) - This is warn message
15/12/2012 23:28:46 [main] FATAL ClientApplication (main:16) - This is fatal message
15/12/2012 23:28:46 [main] ERROR ClientApplication (main:17) - This is error message
Application end successfully

File Output :
[main] DEBUG com.anuj.application.ClientApplication 15/12/2012 23:28:46 - This is debug message
[main] INFO  com.anuj.application.ClientApplication 15/12/2012 23:28:46 - This is info message
[main] WARN  com.anuj.application.ClientApplication 15/12/2012 23:28:46 - This is warn message
[main] FATAL com.anuj.application.ClientApplication 15/12/2012 23:28:46 - This is fatal message
[main] ERROR com.anuj.application.ClientApplication 15/12/2012 23:28:46 - This is error message

Author : Anuj Patel
Blog : http://goldenpackagebyanuj.blogspot.in/

No comments:

Post a Comment