Why do we need a library for logger? doesn’t System.out.println help us enough?
When you try log4j you wouldn’t use System.out.println ever again… (Ok.. you will still used it.. occasionally :p)

What do you need? of course you need to download log4j first 😉 , get it at log4j download page
And open your favorite Java IDE.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
/**
*
* @author jimmy
*/
public class SampleLog4j {

private final static Logger LOGGER = Logger.getLogger(SampleLog4j.class);

public static void main(String[] args) {
PropertyConfigurator.configure(“log4j.properties”);
LOGGER.trace(“Level trace”);
LOGGER.debug(“Level debug”);
LOGGER.info(“Level info”);
LOGGER.warn(“Level warn”);
LOGGER.fatal(“Level fatal”);
}

}

This program will read file log4j.properties in the folder for log4j configuration.
Example of log4j.properties:

### file appender
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=sample.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%n
### console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{ISO8601} — %p %C(%M):%L — %m%nlog4j.rootLogger=debug, console
# uncomment the line below if you want log output to file
# log4j.rootLogger=debug, file

And it’ll produce output:

2007-11-15 18:19:09,812 — DEBUG testing.SampleLog4j(main):26 — Level debug
2007-11-15 18:19:09,828 — INFO testing.SampleLog4j(main):27 — Level info
2007-11-15 18:19:09,828 — WARN testing.SampleLog4j(main):28 — Level warn
2007-11-15 18:19:09,828 — FATAL testing.SampleLog4j(main):29 — Level fatal

Why the log “Level trace” doesn’t logged, because we set the log level only to debug.
You should learn the configuration. There are 2 appender, 1 will log to console and other will log to a file.

Now why shouldn’t I used standard System.out.println?

  • You can’t set the level of log with println only
  • You will end up delete/comment the log using println
  • It won’t be that easy to create log to file with different filename daily (daily-rolling)
  • I wonder how your println can print class name, line number easily 🙂
  • … you can add more after you try it 😉
Advertisements