Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2010-2013 Ning, Inc.
   *
   * Ning licenses this file to you under the Apache License, version 2.0
   * (the "License"); you may not use this file except in compliance with the
   * License.  You may obtain a copy of the License at:
   *
   *    http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
  * License for the specific language governing permissions and limitations
  * under the License.
  */
 package org.slf4j.impl;
 
 import java.util.Date;
 

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

  • org.slf4j.simpleLogger.logFile - The output target which can be the path to a file, or the special values "System.out" and "System.err". Default is "System.err".
  • org.slf4j.simpleLogger.defaultLogLevel - Default log level for all instances of SimpleLogger. Must be one of ("trace", "debug", "info", "warn", or "error"). If not specified, defaults to "info".
  • org.slf4j.simpleLogger.log.a.b.c - Logging detail level for a SimpleLogger instance named "a.b.c". Right-side value must be one of "trace", "debug", "info", "warn", or "error". When a SimpleLogger named "a.b.c" is initialized, its level is assigned from this property. If unspecified, the level of nearest parent logger will be used, and if none is set, then the value specified by org.slf4j.simpleLogger.defaultLogLevel will be used.
  • org.slf4j.simpleLogger.showDateTime - Set to true if you want the current date and time to be included in output messages. Default is true
  • org.slf4j.simpleLogger.dateTimeFormat - The date and time format to be used in the output messages. The pattern describing the date and time format is defined by SimpleDateFormat. If the format is not specified or is invalid, the number of milliseconds since start up will be output.
  • org.slf4j.simpleLogger.showThreadName -Set to true if you want to output the current thread name. Defaults to true.
  • org.slf4j.simpleLogger.showLogName - Set to true if you want the Logger instance name to be included in output messages. Defaults to true.
  • org.slf4j.simpleLogger.showShortLogName - Set to true if you want the last component of the name to be included in output messages. Defaults to false.
  • org.slf4j.simpleLogger.levelInBrackets - Should the level string be output in brackets? Defaults to false.
  • org.slf4j.simpleLogger.warnLevelString - The string value output for the warn level. Defaults to WARN.

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

With no configuration, the default output includes the relative time in milliseconds, thread name, the level, logger name, and the message followed by the line separator for the host. In log4j terms it amounts to the "%r [%t] %level %logger - %m%n" pattern.

Sample output follows.

 176 [main] INFO examples.Sort - Populating an array of 2 elements in reverse order.
 225 [main] INFO examples.SortAlgo - Entered the sort method.
 304 [main] INFO examples.SortAlgo - Dump of integer array:
 317 [main] INFO examples.SortAlgo - Element [0] = 0
 331 [main] INFO examples.SortAlgo - Element [1] = 1
 343 [main] INFO examples.Sort - The next log statement should be an error message.
 346 [main] ERROR examples.SortAlgo - Tried to dump an uninitialized array.
   at org.log4j.examples.SortAlgo.dump(SortAlgo.java:58)
   at org.log4j.examples.Sort.main(Sort.java:64)
 467 [main] INFO  examples.Sort - Exiting main method.
 

This implementation is heavily inspired by Apache Commons Logging's SimpleLog.

Author(s):
Ceki Gülcü
Scott Sanders
Rod Waldhoff
Robert Burrell Donkin
Cédrik LIME
public class SimpleLogger extends MarkerIgnoringBase {
  private static final long serialVersionUID = -632788891211436180L;
  private static final String CONFIGURATION_FILE = "simplelogger.properties";
  private static long START_TIME = System.currentTimeMillis();
  private static final Properties SIMPLE_LOGGER_PROPS = new Properties();
  private static final int LOG_LEVEL_TRACE = .;
  private static final int LOG_LEVEL_DEBUG = .;
  private static final int LOG_LEVEL_INFO = .;
  private static final int LOG_LEVEL_WARN = .;
  private static final int LOG_LEVEL_ERROR = .;
  private static boolean INITIALIZED = false;
  private static int DEFAULT_LOG_LEVEL = ;
  private static boolean SHOW_DATE_TIME = false;
  private static String DATE_TIME_FORMAT_STR = null;
  private static DateFormat DATE_FORMATTER = null;
  private static boolean SHOW_THREAD_NAME = true;
  private static boolean SHOW_LOG_NAME = true;
  private static boolean SHOW_SHORT_LOG_NAME = false;
  private static String LOG_FILE = "System.err";
  private static PrintStream TARGET_STREAM = null;
  private static boolean LEVEL_IN_BRACKETS = false;
  private static String WARN_LEVEL_STRING = "WARN";


  
All system properties used by SimpleLogger start with this prefix
  public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger.";
  public static final String DEFAULT_LOG_LEVEL_KEY =  + "defaultLogLevel";
  public static final String SHOW_DATE_TIME_KEY =  + "showDateTime";
  public static final String DATE_TIME_FORMAT_KEY =  + "dateTimeFormat";
  public static final String SHOW_THREAD_NAME_KEY =  + "showThreadName";
  public static final String SHOW_LOG_NAME_KEY =  + "showLogName";
  public static final String SHOW_SHORT_LOG_NAME_KEY =  + "showShortLogName";
  public static final String LOG_FILE_KEY =  + "logFile";
  public static final String LEVEL_IN_BRACKETS_KEY =  + "levelInBrackets";
  public static final String WARN_LEVEL_STRING_KEY =  + "warnLevelString";
  public static final String LOG_KEY_PREFIX =  + "log.";
  private static String getStringProperty(String name) {
    String prop = null;
    try {
      prop = System.getProperty(name);
    } catch (SecurityException e) {
      ; // Ignore
    }
    return (prop == null) ? .getProperty(name) : prop;
  }
  private static String getStringProperty(String nameString defaultValue) {
    String prop = getStringProperty(name);
    return (prop == null) ? defaultValue : prop;
  }
  private static boolean getBooleanProperty(String nameboolean defaultValue) {
    String prop = getStringProperty(name);
    return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
  }
  // Initialize class attributes.
  // Load properties file, if found.
  // Override with system properties.
  static void init() {
     = true;
    String defaultLogLevelString = getStringProperty(null);
    if (defaultLogLevelString != null)
       = stringToLevel(defaultLogLevelString);
    if ( != null) {
      try {
      } catch (IllegalArgumentException e) {
        Util.report("Bad date format in " +  + "; will output relative time"e);
      }
    }
  }
  private static PrintStream computeTargetStream(String logFile) {
    if ("System.err".equalsIgnoreCase(logFile))
      return .;
    else if ("System.out".equalsIgnoreCase(logFile)) {
      return .;
    } else {
      try {
        FileOutputStream fos = new FileOutputStream(logFile);
        PrintStream printStream = new PrintStream(fos);
        return printStream;
      } catch (FileNotFoundException e) {
        Util.report("Could not open [" + logFile + "]. Defaulting to System.err"e);
        return .;
      }
    }
  }
  private static void loadProperties() {
    // Add props from the resource simplelogger.properties
    InputStream in = (InputStream) AccessController.doPrivileged(
            new PrivilegedAction() {
              public Object run() {
                ClassLoader threadCL = Thread.currentThread().getContextClassLoader();
                if (threadCL != null) {
                  return threadCL.getResourceAsStream();
                } else {
                  return ClassLoader.getSystemResourceAsStream();
                }
              }
            });
    if (null != in) {
      try {
        .load(in);
        in.close();
      } catch (java.io.IOException e) {
        // ignored
      }
    }
  }

  
The current log level
  protected int currentLogLevel = ;
  
The short name of this simple log instance
  private transient String shortLogName = null;

  
Package access allows only SimpleLoggerFactory to instantiate SimpleLogger instances.
  SimpleLogger(String name) {
    if (!) {
      init();
    }
    this. = name;
    String levelString = recursivelyComputeLevelString();
    if (levelString != null) {
      this. = stringToLevel(levelString);
    } else {
    }
  }
    String tempName = ;
    String levelString = null;
    int indexOfLastDot = tempName.length();
    while ((levelString == null) && (indexOfLastDot > -1)) {
      tempName = tempName.substring(0, indexOfLastDot);
      levelString = getStringProperty( + tempNamenull);
      indexOfLastDot = String.valueOf(tempName).lastIndexOf(".");
    }
    return levelString;
  }
  private static int stringToLevel(String levelStr) {
    if ("trace".equalsIgnoreCase(levelStr)) {
      return ;
    } else if ("debug".equalsIgnoreCase(levelStr)) {
      return ;
    } else if ("info".equalsIgnoreCase(levelStr)) {
      return ;
    } else if ("warn".equalsIgnoreCase(levelStr)) {
      return ;
    } else if ("error".equalsIgnoreCase(levelStr)) {
      return ;
    }
    // assume INFO by default
    return ;
  }


  
This is our internal implementation for logging regular (non-parameterized) log messages.

Parameters:
level One of the LOG_LEVEL_XXX constants defining the log level
message The message itself
t The exception whose stack trace should be logged
  protected void log(int levelString messageThrowable t) {
    if (!isLevelEnabled(level)) {
      return;
    }
    StringBuffer buf = new StringBuffer(32);
    // Append date-time if so configured
    if () {
      if ( != null) {
        buf.append(getFormattedDate());
        buf.append(' ');
      } else {
        buf.append(System.currentTimeMillis() - );
        buf.append(' ');
      }
    }
    // Append current thread name if so configured
    if () {
      buf.append('[');
      buf.append(Thread.currentThread().getName());
      buf.append("] ");
    }
    if (buf.append('[');
    // Append a readable representation of the log level
    switch (level) {
      case :
        buf.append("TRACE");
        break;
      case :
        buf.append("DEBUG");
        break;
      case :
        buf.append("INFO");
        break;
      case :
        buf.append();
        break;
      case :
        buf.append("ERROR");
        break;
    }
    if (buf.append(']');
    buf.append(' ');
    // Append the name of the log instance if so configured
    if () {
      if ( == null = computeShortName();
      buf.append(String.valueOf()).append(" - ");
    } else if () {
      buf.append(String.valueOf()).append(" - ");
    }
    // Append the message
    buf.append(message);
    write(buft);
  }
  void write(StringBuffer bufThrowable t) {
    if (t != null) {
    }
  }
  private String getFormattedDate() {
    Date now = new Date();
    String dateText;
    synchronized () {
      dateText = .format(now);
    }
    return dateText;
  }
  private String computeShortName() {
    return .substring(.lastIndexOf(".") + 1);
  }

  
For formatted messages, first substitute arguments and then log.

Parameters:
level
format
arg1
arg2
  private void formatAndLog(int levelString formatObject arg1,
                            Object arg2) {
    if (!isLevelEnabled(level)) {
      return;
    }
    FormattingTuple tp = MessageFormatter.format(formatarg1arg2);
    log(leveltp.getMessage(), tp.getThrowable());
  }

  
For formatted messages, first substitute arguments and then log.

Parameters:
level
format
arguments a list of 3 ore more arguments
  private void formatAndLog(int levelString formatObject... arguments) {
    if (!isLevelEnabled(level)) {
      return;
    }
    FormattingTuple tp = MessageFormatter.arrayFormat(formatarguments);
    log(leveltp.getMessage(), tp.getThrowable());
  }

  
Is the given log level currently enabled?

Parameters:
logLevel is this level enabled?
  protected boolean isLevelEnabled(int logLevel) {
    // log level are numerically ordered so can use simple numeric
    // comparison
    return (logLevel >= );
  }

  
Are trace messages currently enabled?
  public boolean isTraceEnabled() {
  }

  
A simple implementation which logs messages of level TRACE according to the format outlined above.
  public void trace(String msg) {
    log(msgnull);
  }

  
Perform single parameter substitution before logging the message of level TRACE according to the format outlined above.
  public void trace(String formatObject param1) {
    formatAndLog(formatparam1null);
  }

  
Perform double parameter substitution before logging the message of level TRACE according to the format outlined above.
  public void trace(String formatObject param1Object param2) {
    formatAndLog(formatparam1param2);
  }

  
Perform double parameter substitution before logging the message of level TRACE according to the format outlined above.
  public void trace(String formatObject... argArray) {
    formatAndLog(formatargArray);
  }

  
Log a message of level TRACE, including an exception.
  public void trace(String msgThrowable t) {
    log(msgt);
  }

  
Are debug messages currently enabled?
  public boolean isDebugEnabled() {
  }

  
A simple implementation which logs messages of level DEBUG according to the format outlined above.
  public void debug(String msg) {
    log(msgnull);
  }

  
Perform single parameter substitution before logging the message of level DEBUG according to the format outlined above.
  public void debug(String formatObject param1) {
    formatAndLog(formatparam1null);
  }

  
Perform double parameter substitution before logging the message of level DEBUG according to the format outlined above.
  public void debug(String formatObject param1Object param2) {
    formatAndLog(formatparam1param2);
  }

  
Perform double parameter substitution before logging the message of level DEBUG according to the format outlined above.
  public void debug(String formatObject... argArray) {
    formatAndLog(formatargArray);
  }

  
Log a message of level DEBUG, including an exception.
  public void debug(String msgThrowable t) {
    log(msgt);
  }

  
Are info messages currently enabled?
  public boolean isInfoEnabled() {
  }

  
A simple implementation which logs messages of level INFO according to the format outlined above.
  public void info(String msg) {
    log(msgnull);
  }

  
Perform single parameter substitution before logging the message of level INFO according to the format outlined above.
  public void info(String formatObject arg) {
    formatAndLog(formatargnull);
  }

  
Perform double parameter substitution before logging the message of level INFO according to the format outlined above.
  public void info(String formatObject arg1Object arg2) {
    formatAndLog(formatarg1arg2);
  }

  
Perform double parameter substitution before logging the message of level INFO according to the format outlined above.
  public void info(String formatObject... argArray) {
    formatAndLog(formatargArray);
  }

  
Log a message of level INFO, including an exception.
  public void info(String msgThrowable t) {
    log(msgt);
  }

  
Are warn messages currently enabled?
  public boolean isWarnEnabled() {
  }

  
A simple implementation which always logs messages of level WARN according to the format outlined above.
  public void warn(String msg) {
    log(msgnull);
  }

  
Perform single parameter substitution before logging the message of level WARN according to the format outlined above.
  public void warn(String formatObject arg) {
    formatAndLog(formatargnull);
  }

  
Perform double parameter substitution before logging the message of level WARN according to the format outlined above.
  public void warn(String formatObject arg1Object arg2) {
    formatAndLog(formatarg1arg2);
  }

  
Perform double parameter substitution before logging the message of level WARN according to the format outlined above.
  public void warn(String formatObject... argArray) {
    formatAndLog(formatargArray);
  }

  
Log a message of level WARN, including an exception.
  public void warn(String msgThrowable t) {
    log(msgt);
  }

  
Are error messages currently enabled?
  public boolean isErrorEnabled() {
  }

  
A simple implementation which always logs messages of level ERROR according to the format outlined above.
  public void error(String msg) {
    log(msgnull);
  }

  
Perform single parameter substitution before logging the message of level ERROR according to the format outlined above.
  public void error(String formatObject arg) {
    formatAndLog(formatargnull);
  }

  
Perform double parameter substitution before logging the message of level ERROR according to the format outlined above.
  public void error(String formatObject arg1Object arg2) {
    formatAndLog(formatarg1arg2);
  }

  
Perform double parameter substitution before logging the message of level ERROR according to the format outlined above.
  public void error(String formatObject... argArray) {
    formatAndLog(formatargArray);
  }

  
Log a message of level ERROR, including an exception.
  public void error(String msgThrowable t) {
    log(msgt);
  }
New to GrepCode? Check out our FAQ X