FileDocCategorySizeDatePackage
SimpleLog.javaAPI DocAndroid 1.5 API23924Wed May 06 22:41:10 BST 2009org.apache.commons.logging.impl

SimpleLog

public class SimpleLog extends Object implements Serializable, Log

Simple implementation of Log that sends all enabled log messages, for all defined loggers, to System.err. The following system properties are supported to configure the behavior of this logger:

  • org.apache.commons.logging.simplelog.defaultlog - Default logging detail level for all instances of SimpleLog. Must be one of ("trace", "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to "info".
  • org.apache.commons.logging.simplelog.log.xxxxx - Logging detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace", "debug", "info", "warn", "error", or "fatal"). If not specified, the default logging detail level is used.
  • org.apache.commons.logging.simplelog.showlogname - Set to true if you want the Log instance name to be included in output messages. Defaults to false.
  • org.apache.commons.logging.simplelog.showShortLogname - Set to true if you want the last component of the name to be included in output messages. Defaults to true.
  • org.apache.commons.logging.simplelog.showdatetime - Set to true if you want the current date and time to be included in output messages. Default is false.
  • org.apache.commons.logging.simplelog.dateTimeFormat - The date and time format to be used in the output messages. The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. If the format is not specified or is invalid, the default format is used. The default format is yyyy/MM/dd HH:mm:ss:SSS zzz.

In addition to looking for system properties with the names specified above, this implementation also checks for a class loader resource named "simplelog.properties", and includes any matching definitions from this resource (if it exists).

author
Scott Sanders
author
Rod Waldhoff
author
Robert Burrell Donkin
version
$Id: SimpleLog.java 399221 2006-05-03 09:20:24Z dennisl $

Fields Summary
protected static final String
systemPrefix
All system properties used by SimpleLog start with this
protected static final Properties
simpleLogProps
Properties loaded from simplelog.properties
protected static final String
DEFAULT_DATE_TIME_FORMAT
The default format to use when formating dates
protected static boolean
showLogName
Include the instance name in the log message?
protected static boolean
showShortName
Include the short name ( last component ) of the logger in the log message. Defaults to true - otherwise we'll be lost in a flood of messages without knowing who sends them.
protected static boolean
showDateTime
Include the current time in the log message
protected static String
dateTimeFormat
The date and time format to use in the log message
protected static DateFormat
dateFormatter
Used to format times
public static final int
LOG_LEVEL_TRACE
"Trace" level logging.
public static final int
LOG_LEVEL_DEBUG
"Debug" level logging.
public static final int
LOG_LEVEL_INFO
"Info" level logging.
public static final int
LOG_LEVEL_WARN
"Warn" level logging.
public static final int
LOG_LEVEL_ERROR
"Error" level logging.
public static final int
LOG_LEVEL_FATAL
"Fatal" level logging.
public static final int
LOG_LEVEL_ALL
Enable all logging levels
public static final int
LOG_LEVEL_OFF
Enable no logging levels
protected String
logName
The name of this simple log instance
protected int
currentLogLevel
The current log level
private String
shortLogName
The short name of this simple log instance
Constructors Summary
public SimpleLog(String name)
Construct a simple log with given name.

param
name log name



    // ------------------------------------------------------------ Constructor

                    
       

        logName = name;

        // Set initial log level
        // Used to be: set default log level to ERROR
        // IMHO it should be lower, but at least info ( costin ).
        setLevel(SimpleLog.LOG_LEVEL_INFO);

        // Set log level from properties
        String lvl = getStringProperty(systemPrefix + "log." + logName);
        int i = String.valueOf(name).lastIndexOf(".");
        while(null == lvl && i > -1) {
            name = name.substring(0,i);
            lvl = getStringProperty(systemPrefix + "log." + name);
            i = String.valueOf(name).lastIndexOf(".");
        }

        if(null == lvl) {
            lvl =  getStringProperty(systemPrefix + "defaultlog");
        }

        if("all".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_ALL);
        } else if("trace".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_TRACE);
        } else if("debug".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_DEBUG);
        } else if("info".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_INFO);
        } else if("warn".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_WARN);
        } else if("error".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_ERROR);
        } else if("fatal".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_FATAL);
        } else if("off".equalsIgnoreCase(lvl)) {
            setLevel(SimpleLog.LOG_LEVEL_OFF);
        }

    
Methods Summary
public final voiddebug(java.lang.Object message)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_DEBUG.

param
message to log
see
org.apache.commons.logging.Log#debug(Object)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
            log(SimpleLog.LOG_LEVEL_DEBUG, message, null);
        }
    
public final voiddebug(java.lang.Object message, java.lang.Throwable t)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_DEBUG.

param
message to log
param
t log this cause
see
org.apache.commons.logging.Log#debug(Object, Throwable)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
            log(SimpleLog.LOG_LEVEL_DEBUG, message, t);
        }
    
public final voiderror(java.lang.Object message)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_ERROR.

param
message to log
see
org.apache.commons.logging.Log#error(Object)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
            log(SimpleLog.LOG_LEVEL_ERROR, message, null);
        }
    
public final voiderror(java.lang.Object message, java.lang.Throwable t)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_ERROR.

param
message to log
param
t log this cause
see
org.apache.commons.logging.Log#error(Object, Throwable)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
            log(SimpleLog.LOG_LEVEL_ERROR, message, t);
        }
    
public final voidfatal(java.lang.Object message)
Log a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_FATAL.

param
message to log
see
org.apache.commons.logging.Log#fatal(Object)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
            log(SimpleLog.LOG_LEVEL_FATAL, message, null);
        }
    
public final voidfatal(java.lang.Object message, java.lang.Throwable t)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_FATAL.

param
message to log
param
t log this cause
see
org.apache.commons.logging.Log#fatal(Object, Throwable)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
            log(SimpleLog.LOG_LEVEL_FATAL, message, t);
        }
    
private static booleangetBooleanProperty(java.lang.String name, boolean dephault)

        String prop = getStringProperty(name);
        return (prop == null) ? dephault : "true".equalsIgnoreCase(prop);
    
private static java.lang.ClassLoadergetContextClassLoader()
Return the thread context class loader if available. Otherwise return null. The thread context class loader is available for JDK 1.2 or later, if certain security conditions are met.

exception
LogConfigurationException if a suitable class loader cannot be identified.

        ClassLoader classLoader = null;

        if (classLoader == null) {
            try {
                // Are we running on a JDK 1.2 or later system?
                Method method = Thread.class.getMethod("getContextClassLoader",
                        (Class[]) null);

                // Get the thread context class loader (if there is one)
                try {
                    classLoader = (ClassLoader)method.invoke(Thread.currentThread(), 
                            (Object[]) null);

                } catch (IllegalAccessException e) {
                    ;  // ignore
                } catch (InvocationTargetException e) {
                    /**
                     * InvocationTargetException is thrown by 'invoke' when
                     * the method being invoked (getContextClassLoader) throws
                     * an exception.
                     *
                     * getContextClassLoader() throws SecurityException when
                     * the context class loader isn't an ancestor of the
                     * calling class's class loader, or if security
                     * permissions are restricted.
                     *
                     * In the first case (not related), we want to ignore and
                     * keep going.  We cannot help but also ignore the second
                     * with the logic below, but other calls elsewhere (to
                     * obtain a class loader) will trigger this exception where
                     * we can make a distinction.
                     */
                    if (e.getTargetException() instanceof SecurityException) {
                        ;  // ignore
                    } else {
                        // Capture 'e.getTargetException()' exception for details
                        // alternate: log 'e.getTargetException()', and pass back 'e'.
                        throw new LogConfigurationException
                            ("Unexpected InvocationTargetException", e.getTargetException());
                    }
                }
            } catch (NoSuchMethodException e) {
                // Assume we are running on JDK 1.1
                ;  // ignore
            }
        }

        if (classLoader == null) {
            classLoader = SimpleLog.class.getClassLoader();
        }

        // Return the selected class loader
        return classLoader;
    
public intgetLevel()

Get logging level.


        return currentLogLevel;
    
private static java.io.InputStreamgetResourceAsStream(java.lang.String name)

        return (InputStream)AccessController.doPrivileged(
            new PrivilegedAction() {
                public Object run() {
                    ClassLoader threadCL = getContextClassLoader();

                    if (threadCL != null) {
                        return threadCL.getResourceAsStream(name);
                    } else {
                        return ClassLoader.getSystemResourceAsStream(name);
                    }
                }
            });
    
private static java.lang.StringgetStringProperty(java.lang.String name)


    // ------------------------------------------------------------ Initializer

         
        String prop = null;
	try {
	    prop = System.getProperty(name);
	} catch (SecurityException e) {
	    ; // Ignore
	}
        return (prop == null) ? simpleLogProps.getProperty(name) : prop;
    
private static java.lang.StringgetStringProperty(java.lang.String name, java.lang.String dephault)

        String prop = getStringProperty(name);
        return (prop == null) ? dephault : prop;
    
public final voidinfo(java.lang.Object message)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO.

param
message to log
see
org.apache.commons.logging.Log#info(Object)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
            log(SimpleLog.LOG_LEVEL_INFO,message,null);
        }
    
public final voidinfo(java.lang.Object message, java.lang.Throwable t)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO.

param
message to log
param
t log this cause
see
org.apache.commons.logging.Log#info(Object, Throwable)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
            log(SimpleLog.LOG_LEVEL_INFO, message, t);
        }
    
public final booleanisDebugEnabled()

Are debug messages currently enabled?

This allows expensive operations such as String concatenation to be avoided when the message will be ignored by the logger.


        return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG);
    
public final booleanisErrorEnabled()

Are error messages currently enabled?

This allows expensive operations such as String concatenation to be avoided when the message will be ignored by the logger.


        return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR);
    
public final booleanisFatalEnabled()

Are fatal messages currently enabled?

This allows expensive operations such as String concatenation to be avoided when the message will be ignored by the logger.


        return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL);
    
public final booleanisInfoEnabled()

Are info messages currently enabled?

This allows expensive operations such as String concatenation to be avoided when the message will be ignored by the logger.


        return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO);
    
protected booleanisLevelEnabled(int logLevel)
Is the given log level currently enabled?

param
logLevel is this level enabled?

        // log level are numerically ordered so can use simple numeric
        // comparison
        return (logLevel >= currentLogLevel);
    
public final booleanisTraceEnabled()

Are trace messages currently enabled?

This allows expensive operations such as String concatenation to be avoided when the message will be ignored by the logger.


        return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE);
    
public final booleanisWarnEnabled()

Are warn messages currently enabled?

This allows expensive operations such as String concatenation to be avoided when the message will be ignored by the logger.


        return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN);
    
protected voidlog(int type, java.lang.Object message, java.lang.Throwable t)

Do the actual logging. This method assembles the message and then calls write() to cause it to be written.

param
type One of the LOG_LEVEL_XXX constants defining the log level
param
message The message itself (typically a String)
param
t The exception whose stack trace should be logged

        // Use a string buffer for better performance
        StringBuffer buf = new StringBuffer();

        // Append date-time if so configured
        if(showDateTime) {
            buf.append(dateFormatter.format(new Date()));
            buf.append(" ");
        }

        // Append a readable representation of the log level
        switch(type) {
            case SimpleLog.LOG_LEVEL_TRACE: buf.append("[TRACE] "); break;
            case SimpleLog.LOG_LEVEL_DEBUG: buf.append("[DEBUG] "); break;
            case SimpleLog.LOG_LEVEL_INFO:  buf.append("[INFO] ");  break;
            case SimpleLog.LOG_LEVEL_WARN:  buf.append("[WARN] ");  break;
            case SimpleLog.LOG_LEVEL_ERROR: buf.append("[ERROR] "); break;
            case SimpleLog.LOG_LEVEL_FATAL: buf.append("[FATAL] "); break;
        }

        // Append the name of the log instance if so configured
 	if( showShortName) {
            if( shortLogName==null ) {
                // Cut all but the last component of the name for both styles
                shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
                shortLogName =
                    shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
            }
            buf.append(String.valueOf(shortLogName)).append(" - ");
        } else if(showLogName) {
            buf.append(String.valueOf(logName)).append(" - ");
        }

        // Append the message
        buf.append(String.valueOf(message));

        // Append stack trace if not null
        if(t != null) {
            buf.append(" <");
            buf.append(t.toString());
            buf.append(">");

            java.io.StringWriter sw= new java.io.StringWriter(1024);
            java.io.PrintWriter pw= new java.io.PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            buf.append(sw.toString());
        }

        // Print to the appropriate destination
        write(buf);

    
public voidsetLevel(int currentLogLevel)

Set logging level.

param
currentLogLevel new logging level


        this.currentLogLevel = currentLogLevel;

    
public final voidtrace(java.lang.Object message)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_TRACE.

param
message to log
see
org.apache.commons.logging.Log#trace(Object)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
            log(SimpleLog.LOG_LEVEL_TRACE, message, null);
        }
    
public final voidtrace(java.lang.Object message, java.lang.Throwable t)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_TRACE.

param
message to log
param
t log this cause
see
org.apache.commons.logging.Log#trace(Object, Throwable)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
            log(SimpleLog.LOG_LEVEL_TRACE, message, t);
        }
    
public final voidwarn(java.lang.Object message)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_WARN.

param
message to log
see
org.apache.commons.logging.Log#warn(Object)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
            log(SimpleLog.LOG_LEVEL_WARN, message, null);
        }
    
public final voidwarn(java.lang.Object message, java.lang.Throwable t)
Logs a message with org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_WARN.

param
message to log
param
t log this cause
see
org.apache.commons.logging.Log#warn(Object, Throwable)


        if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
            log(SimpleLog.LOG_LEVEL_WARN, message, t);
        }
    
protected voidwrite(java.lang.StringBuffer buffer)

Write the content of the message accumulated in the specified StringBuffer to the appropriate output destination. The default implementation writes to System.err.

param
buffer A StringBuffer containing the accumulated text to be logged


        System.err.println(buffer.toString());