Log4j properties Example

Log4j setup is very easy and it can be configurable in a minute. Now we see different examples of log4j property examples

1. Output to File(Level: DEBUG).
# Root logger option
log4j.rootLogger=DEBUG, file
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender 
log4j.appender.file.File=F:\\App\\javavaillage.log
log4j.appender.file.MaxFileSize=10000KB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p:: %m%n
2. Output to Console
# Root logger option
log4j.rootLogger=INFO, stdout
	 
# Direct log messages to stdout
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::  %m%n
3. Output to Console and File
# Root logger option
log4j.rootLogger=INFO, file, stdout
	 
# Direct log messages to stdout
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:: %m%n

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender 
log4j.appender.file.File=F:\\App\\javavaillage.log
log4j.appender.file.MaxFileSize=10000KB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p:: %m%n

4. How to Append class name, method name and line number: This is useful whenever you want to track any specific issue and this is not recocommended to use always. See below link for more details
http://www.javavillage.in/view-topic.php?tag=enable-class-name-and-method-name-to-display-in-logs

# Root logger option
log4j.rootLogger=INFO, stdout
	 
# Direct log messages to stdout
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:%M:%L]:: %m%n

Execute the class (Log4jMain.java) with above log4j.property changes

  2014-10-28 12:42:54 INFO  [com.javavillage.dozer.Log4jMain:main:9]:: Hi Log4j
  2014-10-28 12:42:54 ERROR [com.javavillage.dozer.Log4jMain:main:11]:: Hi Log4j, This is an Error

Note: If you want to specify only class name without package name use %c{1} instead of %C

  2014-10-28 12:42:54 INFO  [Log4jMain:main:9]:: Hi Log4j
  2014-10-28 12:42:54 ERROR [Log4jMain:main:11]:: Hi Log4j, This is an Error