CVS: jfor/src/org/jfor/jfor/main JForLogConfig.java,NONE,1.1

Bertrand Delacretaz <[email protected]> Tue, 24 Sep 2002 03:13:19 -0700
Newsgroups gmane.text.xml.jfor.cvs
Message-ID <[email protected]>
Update of /cvsroot/jfor/jfor/src/org/jfor/jfor/main
In directory usw-pr-cvs1:/tmp/cvs-serv15398/src/org/jfor/jfor/main

Added Files:
	JForLogConfig.java 
Log Message:
 V0.7.2dev-e - uses Apache logkit for more precise and configurable logging

--- NEW FILE: JForLogConfig.java ---
package org.jfor.jfor.main;

import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.Iterator;
import org.apache.log.Hierarchy; 
import org.apache.log.Priority; 
import org.apache.log.Logger;
import org.apache.log.LogTarget;
import org.apache.log.format.PatternFormatter;
import org.apache.log.output.io.StreamTarget;
 
/*-----------------------------------------------------------------------------
 * jfor - Open-Source XSL-FO to RTF converter - see www.jfor.org
 *
 * ====================================================================
 * jfor Apache-Style Software License.
 * Copyright (c) 2002 by the jfor project. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 * if any, must include the following acknowledgment:
 * "This product includes software developed
 * by the jfor project (http://www.jfor.org)."
 * Alternately, this acknowledgment may appear in the software itself,
 * if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The name "jfor" must not be used to endorse
 * or promote products derived from this software without prior written
 * permission.  For written permission, please contact [email protected].
 *
 * 5. Products derived from this software may not be called "jfor",
 * nor may "jfor" appear in their name, without prior written
 * permission of [email protected].
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE JFOR PROJECT OR ITS CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 * Contributor(s):
 *  @author Andreas Putz [email protected]
-----------------------------------------------------------------------------*/

/**     Configures log4j for the jfor logging system.
 *      @author Bertrand Delacretaz [email protected]
 */

//------------------------------------------------------------------------------
// $Id: JForLogConfig.java,v 1.1 2002/09/24 10:13:17 bdelacretaz Exp $
// $Log: JForLogConfig.java,v $
// Revision 1.1  2002/09/24 10:13:17  bdelacretaz
//  V0.7.2dev-e - uses Apache logkit for more precise and configurable logging
//
//------------------------------------------------------------------------------

public class JForLogConfig
{
    private static boolean m_configured;

    /** our own log category */
    private static final Logger m_logger = Hierarchy.getDefaultHierarchy().getLoggerFor("jfor.logger.config");
    
    /** prefix for system properties */
    private static final String PROP_PREFIX = "log.priority.";    
    
    /** default priorities for some log categories  */
    private static final Map m_defPrio = new TreeMap();
    static {
        m_defPrio.put("jfor",Priority.INFO),
        m_defPrio.put("jfor.converter.sax.events",Priority.WARN);
        m_defPrio.put("jfor.converter.builder.actions",Priority.WARN);
    }
    
    /** Must be called before using any log4j Logger
     *  By default, configures log4j to use System.err for logging.
     *  Might be improved for better control of what is logged and what is not
     */
    public static void configure()
    {
        synchronized(JForLogConfig.class) {
            if(m_configured) return;
            if(!runningUnderCocoon()) {
                defaultToConsole();
                configureCategories();
            }
            m_configured = true;
        }
    }

    /** configure the priorities of relevant log categories */     
    private static void configureCategories()
    {
        for(Iterator it = m_defPrio.entrySet().iterator(); it.hasNext(); ) {
            final Map.Entry e = (Map.Entry)it.next();
            final String name = (String)e.getKey();
            final Priority p = getPriorityForCategory(name,(Priority)e.getValue());
            
            Hierarchy.getDefaultHierarchy().getLoggerFor(name).setPriority(p);
            if(m_logger.isInfoEnabled()) {
                m_logger.info("Priority of log category '" + name + "' set to '" + p + "'");
            }
        }            
        if(m_logger.isInfoEnabled()) {
            m_logger.info(
            "System properties can be used to set log priorities, "
            + "using '-Dlog.priority.jfor.converter.builder.actions=debug', for example "
            + "would activate the DEBUG level of the jfor.converter.builder.actions category"
            );
        }
    }

    /** maybe override p with value given by system property */
    private static Priority getPriorityForCategory(String name,Priority p)
    {
        final String propName = PROP_PREFIX + name;
        Priority result = p;
        final String prop = System.getProperty(propName);
        if(prop != null) {
            if(m_logger.isDebugEnabled()) {
                m_logger.debug("System property '" + propName + "' overrides log priority for corresponding category with value '" + prop + "'"); 
            }
            result = Priority.getPriorityForName(prop);
        }
        return result;
    }
    
    /** find out if we're running in the Cocoon environment.
     *  Actually we'd rather like to find if logkit is already configured, but how?
     *  Logger.getLogTargets is deprecated, and I don't see another way to find out
     */
    private boolean runningUnderCocoon()
    {
        // try to load a class from Cocoon - if ok assume we're running under Cocoon
        // which will take care of logkit configuration
        final String testClass = "org.apache.cocoon.serialization.RTFSerializer";
        boolean result = false;
        try {
            class.forName(testClass);
            result = true;
        } catch(Exception ignoreThisException) {}
        
        if(m_logger.isDebugEnabled()) {
            if(result) {
                m_logger.debug(
                "Attempt to load class '" + testClass + "'"
                + (result ? "successful" : "failed")
                + ", runningUnderCocoon()=" + result
                );
            }
        }
        
        return result;
    }     
            
    /** default configuration, configures log4j to write System.err unless already configured */
    private static void defaultToConsole()
    {
        final PatternFormatter fmt = new PatternFormatter("[%{category}] {%{priority}} %{message}\n");
        final StreamTarget stderr = new StreamTarget(System.err,fmt);
        final Logger jforRootLogger = Hierarchy.getDefaultHierarchy().getLoggerFor("jfor");
        jforRootLogger.setLogTargets(new LogTarget[] {stderr});
    }     
}



-------------------------------------------------------
This sf.net email is sponsored by:ThinkGeek
Welcome to geek heaven.
http://thinkgeek.com/sf