Changeset 6722


Ignore:
Timestamp:
07/21/10 17:36:39 (9 years ago)
Author:
curtis
Message:

Add a utility method for enabling log4j logging without a configuration file.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/components/common/src/loci/common/DebugTools.java

    r6318 r6722  
    2626import java.io.ByteArrayOutputStream; 
    2727import java.io.PrintStream; 
     28import java.util.Enumeration; 
    2829 
    2930/** 
     
    5152  } 
    5253 
     54  /** 
     55   * Attempts to enable SLF4J logging via log4j 
     56   * without an external configuration file. 
     57   * 
     58   * @param level A string indicating the desired level 
     59   *   (i.e.: ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN). 
     60   * @return true iff logging was successfully enabled 
     61   */ 
     62  public static synchronized boolean enableLogging(String level) { 
     63    ReflectedUniverse r = new ReflectedUniverse(); 
     64    try { 
     65      r.exec("import org.apache.log4j.Level"); 
     66      r.exec("import org.apache.log4j.Logger"); 
     67      r.exec("root = Logger.getRootLogger()"); 
     68      r.exec("root.setLevel(Level." + level + ")"); 
     69      Enumeration en = (Enumeration) r.exec("root.getAllAppenders()"); 
     70      if (!en.hasMoreElements()) { 
     71        // no appenders yet; attach a simple console appender 
     72        r.exec("import org.apache.log4j.ConsoleAppender"); 
     73        r.exec("import org.apache.log4j.PatternLayout"); 
     74        r.setVar("pattern", "%m%n"); 
     75        r.exec("layout = new PatternLayout(pattern)"); 
     76        r.exec("appender = new ConsoleAppender(layout)"); 
     77        r.exec("root.addAppender(appender)"); 
     78      } 
     79    } 
     80    catch (ReflectException exc) { 
     81      return false; 
     82    } 
     83    return true; 
     84  } 
     85 
    5386} 
Note: See TracChangeset for help on using the changeset viewer.