Thursday, May 10, 2007

How to setup our JAVA project to work with Log4j

  1. First, you will need 2 library files that are log4j-xxxx.jar and commons-logging-xxxx.jar. Which xxxx is version number. Affter that, add them into your project libraries.

  2. Create file name and paste it in your project class path. It will be copied into classes folder automatically.

    For example; If you project class path is src folder. Then this should be in src folder.

    After you already have file. This is the example code in the properties file.

    log4j.rootLogger = DEBUG, A1
    log4j.appender.A1 = org.apache.log4j.ConsoleAppender
    log4j.appender.A1.layout = org.apache.log4j.PatternLayout
    log4j.appender.A1.layout.ConversionPattern = %-7r %d [%t] %-5p %c -%m%n

    In the first line, the first parameter is level of logging that you need to configure. If you need to log DEBUG level, use DEBUG. But if you need to log INFO level, put INFO instead of DEBUG. By the way, DEBUG is rather bigger than INFO.

    In the second line, it means that you need to show log in the console.

    In the last line, you can configure pattern of your log here.

  3. In your java file, all you need is declare log and use it, like this;

    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;

    public class TestLog {

    private static final Log logger = LogFactory.getLog(TestLog.class);

    public static void main(String[] args) {
    logger.debug("This is my first logging.");
    logger.debug("This is my second logging.");


    The parameter that you need in the LogFactory.getLog() is your class name that you want to show when log is presented on the console.

    0 2550-05-10 11:22:02,908 [main] DEBUG TestLog - This is my first logging.
    0 2550-05-10 11:22:02,908 [main] DEBUG TestLog - This is my second logging.

No comments: