= Log4j wiki migrated to a [http://wiki.apache.org/logging-log4j/Log4JProjectPages new home]. This page is no longer updated! =


Log4j Code Bits

Please use this page to list classes or code bits related to log4j that you have found to be useful. If you have found them to be useful, chances are so will someone else.

Click here to add your submissions.


Determining the running version of log4j:

import  org.apache.log4j.Layout;
public class X {
{{{   public static void main(String[] a) { 
     Package p = Layout.class.getPackage(); 
     System.out.println(p); 
     System.out.println("Implementation title:   "+p.getImplementationTitle()); 
     System.out.println("Implementation vendor:  "+p.getImplementationVendor()); 
     System.out.println("Implementation version: "+p.getImplementationVersion()); 
   } 

}

yields:

package org.apache.log4j Implementation title: log4j Implementation vendor: "Apache Software Foundation" Implementation version: 1.2.8 <-- that's what you are looking for

It will yield the expected results with log4j 1.1.x as well as 1.2.x. Thanks to Daniel Serodio for the suggestion and Ceki for the code


Various code bits that extend or user log4j classes and features have been submitted by many contributors. They can be found as part of the log4j release package or here.


["SNMPTrapAppender"] is a third party, open source appender that sends log messages via SNMP traps.


Some (hopefully) useful filters can be found in the current log4j cvs at http://cvs.apache.org/viewcvs/jakarta-log4j-sandbox/src/java/org/apache/log4j/filter/. They will be released, in some packaged form, with v1.3, but they are compatible with current v1.2.X.


Some custom repository selectors can be found in the current log4j cvs at http://cvs.apache.org/viewcvs/jakarta-log4j-sandbox/src/java/org/apache/log4j/selector/. They will be released, in some packaged form, with v1.3, but they are compatible with current v1.2.X.


Web Application - Servlet related log4j classes can be found in the current log4j cvs at http://cvs.apache.org/viewcvs/jakarta-log4j-sandbox/src/java/org/apache/log4j/servlet/. They will be released, in some packaged form, with v1.3, but they are compatible with the current v1.2.X.


This bit of code can be used to "guess" if log4j has been previously configured. It does not determine if the configuration is valid and working as expected.

    /** 
        Returns true if it appears that log4j have been previously configured. This code 
        checks to see if there are any appenders defined for log4j which is the 
        definitive way to tell if log4j is already initialized */ 
    private static boolean isConfigured() { 
        Enumeration enum = Logger.getRoot().getAllAppenders(); 
        if ((enum != null) && (!(enum instanceof org.apache.log4j.helpers.NullEnumeration))) { 
            return true; 
        } 
        else { 
            Enumeration loggers = LogManager.getCurrentLoggers() ; 
            while (loggers.hasMoreElements()) { 
                Logger c = (Logger) loggers.nextElement(); 
                if (!(c.getAllAppenders() instanceof org.apache.log4j.helpers.NullEnumeration)) 
                    return true; 
            } 
        } 
        return false; 
    } 

Or instead of guessing if log4j has been previously configured, you might want to ensure that it is configured (or shut down for that matter) only once. Here is a class that does just that. This can be particularly useful for JUnit test cases as methods configure and shutdown can be called from methods setUp() and tearDown(), respectively, of JUnit test cases.

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.LogManager;

public class Log4jConfigurator {

{{{    private static boolean configured = false; 

    public synchronized static void configure() { 
        if (!configured) { 
            BasicConfigurator.configure(); 
            configured = true; 
        } 
    } 

    public synchronized static void shutdown() { 
        if (configured) { 
            LogManager.shutdown(); 
            configured = false; 
        } 
    } 

}


Using Log4j with libs that log to a java.io.Writer, E.g. javax.sql.DataSource:

Thanks to Gino Marckx for suggesting a FilterWriter extension in his sample

import java.io.*;
import org.apache.log4j.Logger;
import org.apache.log4j.Level;

/** A java.io.Writer implementation that forwards the stream to
{{{ * a Log4j logger. This allows the use of Log4j with third-party 
 * APIs that can only write log messages to a stream. E.g. JDBC's 
 * javax.sql.DataSource implementations accept a java.io.PrintWriter 
 * instance to which all log messages are written. We can forward these 
 * jdbc log messages to log4j using 
 * <code> 
 *   dataSource.setLogWriter 
 *     (new PrinterWriter 
 *      (new Writer2Log4j("logger.category","debug",true))); 
 * </code>. 
 * How do we decide on the boundaries of messages in the stream of 
 * characters? We rely on the <code>flush()</code> method. 
 * 
 * @revision $Revision$ $Date$ 
 * @author Prasad Chodavarapu (http://chap.aalayance.com/) 
 */ 

public class Writer2Log4j extends FilterWriter {

{{{ protected final Logger logger;

}

Log4JProjectPages/UsefulCode (last edited 2009-09-20 23:32:24 by localhost)