1. /*
  2. * Copyright 2001-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.logging.impl;
  17. import java.io.InputStream;
  18. import java.io.Serializable;
  19. import java.lang.reflect.InvocationTargetException;
  20. import java.lang.reflect.Method;
  21. import java.security.AccessController;
  22. import java.security.PrivilegedAction;
  23. import java.text.DateFormat;
  24. import java.text.SimpleDateFormat;
  25. import java.util.Date;
  26. import java.util.Properties;
  27. import org.apache.commons.logging.Log;
  28. import org.apache.commons.logging.LogConfigurationException;
  29. /**
  30. * <p>Simple implementation of Log that sends all enabled log messages,
  31. * for all defined loggers, to System.err. The following system properties
  32. * are supported to configure the behavior of this logger:</p>
  33. * <ul>
  34. * <li><code>org.apache.commons.logging.simplelog.defaultlog</code> -
  35. * Default logging detail level for all instances of SimpleLog.
  36. * Must be one of ("trace", "debug", "info", "warn", "error", or "fatal").
  37. * If not specified, defaults to "info". </li>
  38. * <li><code>org.apache.commons.logging.simplelog.log.xxxxx</code> -
  39. * Logging detail level for a SimpleLog instance named "xxxxx".
  40. * Must be one of ("trace", "debug", "info", "warn", "error", or "fatal").
  41. * If not specified, the default logging detail level is used.</li>
  42. * <li><code>org.apache.commons.logging.simplelog.showlogname</code> -
  43. * Set to <code>true</code> if you want the Log instance name to be
  44. * included in output messages. Defaults to <code>false</code>.</li>
  45. * <li><code>org.apache.commons.logging.simplelog.showShortLogname</code> -
  46. * Set to <code>true</code> if you want the last component of the name to be
  47. * included in output messages. Defaults to <code>true</code>.</li>
  48. * <li><code>org.apache.commons.logging.simplelog.showdatetime</code> -
  49. * Set to <code>true</code> if you want the current date and time
  50. * to be included in output messages. Default is <code>false</code>.</li>
  51. * <li><code>org.apache.commons.logging.simplelog.dateTimeFormat</code> -
  52. * The date and time format to be used in the output messages.
  53. * The pattern describing the date and time format is the same that is
  54. * used in <code>java.text.SimpleDateFormat</code>. If the format is not
  55. * specified or is invalid, the default format is used.
  56. * The default format is <code>yyyy/MM/dd HH:mm:ss:SSS zzz</code>.</li>
  57. * </ul>
  58. *
  59. * <p>In addition to looking for system properties with the names specified
  60. * above, this implementation also checks for a class loader resource named
  61. * <code>"simplelog.properties"</code>, and includes any matching definitions
  62. * from this resource (if it exists).</p>
  63. *
  64. * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
  65. * @author Rod Waldhoff
  66. * @author Robert Burrell Donkin
  67. *
  68. * @version $Id: SimpleLog.java,v 1.21 2004/06/06 20:47:56 rdonkin Exp $
  69. */
  70. public class SimpleLog implements Log, Serializable {
  71. // ------------------------------------------------------- Class Attributes
  72. /** All system properties used by <code>SimpleLog</code> start with this */
  73. static protected final String systemPrefix =
  74. "org.apache.commons.logging.simplelog.";
  75. /** Properties loaded from simplelog.properties */
  76. static protected final Properties simpleLogProps = new Properties();
  77. /** The default format to use when formating dates */
  78. static protected final String DEFAULT_DATE_TIME_FORMAT =
  79. "yyyy/MM/dd HH:mm:ss:SSS zzz";
  80. /** Include the instance name in the log message? */
  81. static protected boolean showLogName = false;
  82. /** Include the short name ( last component ) of the logger in the log
  83. * message. Defaults to true - otherwise we'll be lost in a flood of
  84. * messages without knowing who sends them.
  85. */
  86. static protected boolean showShortName = true;
  87. /** Include the current time in the log message */
  88. static protected boolean showDateTime = false;
  89. /** The date and time format to use in the log message */
  90. static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
  91. /** Used to format times */
  92. static protected DateFormat dateFormatter = null;
  93. // ---------------------------------------------------- Log Level Constants
  94. /** "Trace" level logging. */
  95. public static final int LOG_LEVEL_TRACE = 1;
  96. /** "Debug" level logging. */
  97. public static final int LOG_LEVEL_DEBUG = 2;
  98. /** "Info" level logging. */
  99. public static final int LOG_LEVEL_INFO = 3;
  100. /** "Warn" level logging. */
  101. public static final int LOG_LEVEL_WARN = 4;
  102. /** "Error" level logging. */
  103. public static final int LOG_LEVEL_ERROR = 5;
  104. /** "Fatal" level logging. */
  105. public static final int LOG_LEVEL_FATAL = 6;
  106. /** Enable all logging levels */
  107. public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1);
  108. /** Enable no logging levels */
  109. public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1);
  110. // ------------------------------------------------------------ Initializer
  111. private static String getStringProperty(String name) {
  112. String prop = null;
  113. try {
  114. prop = System.getProperty(name);
  115. } catch (SecurityException e) {
  116. ; // Ignore
  117. }
  118. return (prop == null) ? simpleLogProps.getProperty(name) : prop;
  119. }
  120. private static String getStringProperty(String name, String dephault) {
  121. String prop = getStringProperty(name);
  122. return (prop == null) ? dephault : prop;
  123. }
  124. private static boolean getBooleanProperty(String name, boolean dephault) {
  125. String prop = getStringProperty(name);
  126. return (prop == null) ? dephault : "true".equalsIgnoreCase(prop);
  127. }
  128. // Initialize class attributes.
  129. // Load properties file, if found.
  130. // Override with system properties.
  131. static {
  132. // Add props from the resource simplelog.properties
  133. InputStream in = getResourceAsStream("simplelog.properties");
  134. if(null != in) {
  135. try {
  136. simpleLogProps.load(in);
  137. in.close();
  138. } catch(java.io.IOException e) {
  139. // ignored
  140. }
  141. }
  142. showLogName = getBooleanProperty( systemPrefix + "showlogname", showLogName);
  143. showShortName = getBooleanProperty( systemPrefix + "showShortLogname", showShortName);
  144. showDateTime = getBooleanProperty( systemPrefix + "showdatetime", showDateTime);
  145. if(showDateTime) {
  146. dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat",
  147. dateTimeFormat);
  148. try {
  149. dateFormatter = new SimpleDateFormat(dateTimeFormat);
  150. } catch(IllegalArgumentException e) {
  151. // If the format pattern is invalid - use the default format
  152. dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
  153. dateFormatter = new SimpleDateFormat(dateTimeFormat);
  154. }
  155. }
  156. }
  157. // ------------------------------------------------------------- Attributes
  158. /** The name of this simple log instance */
  159. protected String logName = null;
  160. /** The current log level */
  161. protected int currentLogLevel;
  162. /** The short name of this simple log instance */
  163. private String shortLogName = null;
  164. // ------------------------------------------------------------ Constructor
  165. /**
  166. * Construct a simple log with given name.
  167. *
  168. * @param name log name
  169. */
  170. public SimpleLog(String name) {
  171. logName = name;
  172. // Set initial log level
  173. // Used to be: set default log level to ERROR
  174. // IMHO it should be lower, but at least info ( costin ).
  175. setLevel(SimpleLog.LOG_LEVEL_INFO);
  176. // Set log level from properties
  177. String lvl = getStringProperty(systemPrefix + "log." + logName);
  178. int i = String.valueOf(name).lastIndexOf(".");
  179. while(null == lvl && i > -1) {
  180. name = name.substring(0,i);
  181. lvl = getStringProperty(systemPrefix + "log." + name);
  182. i = String.valueOf(name).lastIndexOf(".");
  183. }
  184. if(null == lvl) {
  185. lvl = getStringProperty(systemPrefix + "defaultlog");
  186. }
  187. if("all".equalsIgnoreCase(lvl)) {
  188. setLevel(SimpleLog.LOG_LEVEL_ALL);
  189. } else if("trace".equalsIgnoreCase(lvl)) {
  190. setLevel(SimpleLog.LOG_LEVEL_TRACE);
  191. } else if("debug".equalsIgnoreCase(lvl)) {
  192. setLevel(SimpleLog.LOG_LEVEL_DEBUG);
  193. } else if("info".equalsIgnoreCase(lvl)) {
  194. setLevel(SimpleLog.LOG_LEVEL_INFO);
  195. } else if("warn".equalsIgnoreCase(lvl)) {
  196. setLevel(SimpleLog.LOG_LEVEL_WARN);
  197. } else if("error".equalsIgnoreCase(lvl)) {
  198. setLevel(SimpleLog.LOG_LEVEL_ERROR);
  199. } else if("fatal".equalsIgnoreCase(lvl)) {
  200. setLevel(SimpleLog.LOG_LEVEL_FATAL);
  201. } else if("off".equalsIgnoreCase(lvl)) {
  202. setLevel(SimpleLog.LOG_LEVEL_OFF);
  203. }
  204. }
  205. // -------------------------------------------------------- Properties
  206. /**
  207. * <p> Set logging level. </p>
  208. *
  209. * @param currentLogLevel new logging level
  210. */
  211. public void setLevel(int currentLogLevel) {
  212. this.currentLogLevel = currentLogLevel;
  213. }
  214. /**
  215. * <p> Get logging level. </p>
  216. */
  217. public int getLevel() {
  218. return currentLogLevel;
  219. }
  220. // -------------------------------------------------------- Logging Methods
  221. /**
  222. * <p> Do the actual logging.
  223. * This method assembles the message
  224. * and then calls <code>write()</code> to cause it to be written.</p>
  225. *
  226. * @param type One of the LOG_LEVEL_XXX constants defining the log level
  227. * @param message The message itself (typically a String)
  228. * @param t The exception whose stack trace should be logged
  229. */
  230. protected void log(int type, Object message, Throwable t) {
  231. // Use a string buffer for better performance
  232. StringBuffer buf = new StringBuffer();
  233. // Append date-time if so configured
  234. if(showDateTime) {
  235. buf.append(dateFormatter.format(new Date()));
  236. buf.append(" ");
  237. }
  238. // Append a readable representation of the log level
  239. switch(type) {
  240. case SimpleLog.LOG_LEVEL_TRACE: buf.append("[TRACE] "); break;
  241. case SimpleLog.LOG_LEVEL_DEBUG: buf.append("[DEBUG] "); break;
  242. case SimpleLog.LOG_LEVEL_INFO: buf.append("[INFO] "); break;
  243. case SimpleLog.LOG_LEVEL_WARN: buf.append("[WARN] "); break;
  244. case SimpleLog.LOG_LEVEL_ERROR: buf.append("[ERROR] "); break;
  245. case SimpleLog.LOG_LEVEL_FATAL: buf.append("[FATAL] "); break;
  246. }
  247. // Append the name of the log instance if so configured
  248. if( showShortName) {
  249. if( shortLogName==null ) {
  250. // Cut all but the last component of the name for both styles
  251. shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
  252. shortLogName =
  253. shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
  254. }
  255. buf.append(String.valueOf(shortLogName)).append(" - ");
  256. } else if(showLogName) {
  257. buf.append(String.valueOf(logName)).append(" - ");
  258. }
  259. // Append the message
  260. buf.append(String.valueOf(message));
  261. // Append stack trace if not null
  262. if(t != null) {
  263. buf.append(" <");
  264. buf.append(t.toString());
  265. buf.append(">");
  266. java.io.StringWriter sw= new java.io.StringWriter(1024);
  267. java.io.PrintWriter pw= new java.io.PrintWriter(sw);
  268. t.printStackTrace(pw);
  269. pw.close();
  270. buf.append(sw.toString());
  271. }
  272. // Print to the appropriate destination
  273. write(buf);
  274. }
  275. /**
  276. * <p>Write the content of the message accumulated in the specified
  277. * <code>StringBuffer</code> to the appropriate output destination. The
  278. * default implementation writes to <code>System.err</code>.</p>
  279. *
  280. * @param buffer A <code>StringBuffer</code> containing the accumulated
  281. * text to be logged
  282. */
  283. protected void write(StringBuffer buffer) {
  284. System.err.println(buffer.toString());
  285. }
  286. /**
  287. * Is the given log level currently enabled?
  288. *
  289. * @param logLevel is this level enabled?
  290. */
  291. protected boolean isLevelEnabled(int logLevel) {
  292. // log level are numerically ordered so can use simple numeric
  293. // comparison
  294. return (logLevel >= currentLogLevel);
  295. }
  296. // -------------------------------------------------------- Log Implementation
  297. /**
  298. * <p> Log a message with debug log level.</p>
  299. */
  300. public final void debug(Object message) {
  301. if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
  302. log(SimpleLog.LOG_LEVEL_DEBUG, message, null);
  303. }
  304. }
  305. /**
  306. * <p> Log an error with debug log level.</p>
  307. */
  308. public final void debug(Object message, Throwable t) {
  309. if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
  310. log(SimpleLog.LOG_LEVEL_DEBUG, message, t);
  311. }
  312. }
  313. /**
  314. * <p> Log a message with trace log level.</p>
  315. */
  316. public final void trace(Object message) {
  317. if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
  318. log(SimpleLog.LOG_LEVEL_TRACE, message, null);
  319. }
  320. }
  321. /**
  322. * <p> Log an error with trace log level.</p>
  323. */
  324. public final void trace(Object message, Throwable t) {
  325. if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
  326. log(SimpleLog.LOG_LEVEL_TRACE, message, t);
  327. }
  328. }
  329. /**
  330. * <p> Log a message with info log level.</p>
  331. */
  332. public final void info(Object message) {
  333. if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
  334. log(SimpleLog.LOG_LEVEL_INFO,message,null);
  335. }
  336. }
  337. /**
  338. * <p> Log an error with info log level.</p>
  339. */
  340. public final void info(Object message, Throwable t) {
  341. if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
  342. log(SimpleLog.LOG_LEVEL_INFO, message, t);
  343. }
  344. }
  345. /**
  346. * <p> Log a message with warn log level.</p>
  347. */
  348. public final void warn(Object message) {
  349. if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
  350. log(SimpleLog.LOG_LEVEL_WARN, message, null);
  351. }
  352. }
  353. /**
  354. * <p> Log an error with warn log level.</p>
  355. */
  356. public final void warn(Object message, Throwable t) {
  357. if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
  358. log(SimpleLog.LOG_LEVEL_WARN, message, t);
  359. }
  360. }
  361. /**
  362. * <p> Log a message with error log level.</p>
  363. */
  364. public final void error(Object message) {
  365. if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
  366. log(SimpleLog.LOG_LEVEL_ERROR, message, null);
  367. }
  368. }
  369. /**
  370. * <p> Log an error with error log level.</p>
  371. */
  372. public final void error(Object message, Throwable t) {
  373. if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
  374. log(SimpleLog.LOG_LEVEL_ERROR, message, t);
  375. }
  376. }
  377. /**
  378. * <p> Log a message with fatal log level.</p>
  379. */
  380. public final void fatal(Object message) {
  381. if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
  382. log(SimpleLog.LOG_LEVEL_FATAL, message, null);
  383. }
  384. }
  385. /**
  386. * <p> Log an error with fatal log level.</p>
  387. */
  388. public final void fatal(Object message, Throwable t) {
  389. if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
  390. log(SimpleLog.LOG_LEVEL_FATAL, message, t);
  391. }
  392. }
  393. /**
  394. * <p> Are debug messages currently enabled? </p>
  395. *
  396. * <p> This allows expensive operations such as <code>String</code>
  397. * concatenation to be avoided when the message will be ignored by the
  398. * logger. </p>
  399. */
  400. public final boolean isDebugEnabled() {
  401. return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG);
  402. }
  403. /**
  404. * <p> Are error messages currently enabled? </p>
  405. *
  406. * <p> This allows expensive operations such as <code>String</code>
  407. * concatenation to be avoided when the message will be ignored by the
  408. * logger. </p>
  409. */
  410. public final boolean isErrorEnabled() {
  411. return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR);
  412. }
  413. /**
  414. * <p> Are fatal messages currently enabled? </p>
  415. *
  416. * <p> This allows expensive operations such as <code>String</code>
  417. * concatenation to be avoided when the message will be ignored by the
  418. * logger. </p>
  419. */
  420. public final boolean isFatalEnabled() {
  421. return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL);
  422. }
  423. /**
  424. * <p> Are info messages currently enabled? </p>
  425. *
  426. * <p> This allows expensive operations such as <code>String</code>
  427. * concatenation to be avoided when the message will be ignored by the
  428. * logger. </p>
  429. */
  430. public final boolean isInfoEnabled() {
  431. return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO);
  432. }
  433. /**
  434. * <p> Are trace messages currently enabled? </p>
  435. *
  436. * <p> This allows expensive operations such as <code>String</code>
  437. * concatenation to be avoided when the message will be ignored by the
  438. * logger. </p>
  439. */
  440. public final boolean isTraceEnabled() {
  441. return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE);
  442. }
  443. /**
  444. * <p> Are warn messages currently enabled? </p>
  445. *
  446. * <p> This allows expensive operations such as <code>String</code>
  447. * concatenation to be avoided when the message will be ignored by the
  448. * logger. </p>
  449. */
  450. public final boolean isWarnEnabled() {
  451. return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN);
  452. }
  453. /**
  454. * Return the thread context class loader if available.
  455. * Otherwise return null.
  456. *
  457. * The thread context class loader is available for JDK 1.2
  458. * or later, if certain security conditions are met.
  459. *
  460. * @exception LogConfigurationException if a suitable class loader
  461. * cannot be identified.
  462. */
  463. private static ClassLoader getContextClassLoader()
  464. {
  465. ClassLoader classLoader = null;
  466. if (classLoader == null) {
  467. try {
  468. // Are we running on a JDK 1.2 or later system?
  469. Method method = Thread.class.getMethod("getContextClassLoader", null);
  470. // Get the thread context class loader (if there is one)
  471. try {
  472. classLoader = (ClassLoader)method.invoke(Thread.currentThread(), null);
  473. } catch (IllegalAccessException e) {
  474. ; // ignore
  475. } catch (InvocationTargetException e) {
  476. /**
  477. * InvocationTargetException is thrown by 'invoke' when
  478. * the method being invoked (getContextClassLoader) throws
  479. * an exception.
  480. *
  481. * getContextClassLoader() throws SecurityException when
  482. * the context class loader isn't an ancestor of the
  483. * calling class's class loader, or if security
  484. * permissions are restricted.
  485. *
  486. * In the first case (not related), we want to ignore and
  487. * keep going. We cannot help but also ignore the second
  488. * with the logic below, but other calls elsewhere (to
  489. * obtain a class loader) will trigger this exception where
  490. * we can make a distinction.
  491. */
  492. if (e.getTargetException() instanceof SecurityException) {
  493. ; // ignore
  494. } else {
  495. // Capture 'e.getTargetException()' exception for details
  496. // alternate: log 'e.getTargetException()', and pass back 'e'.
  497. throw new LogConfigurationException
  498. ("Unexpected InvocationTargetException", e.getTargetException());
  499. }
  500. }
  501. } catch (NoSuchMethodException e) {
  502. // Assume we are running on JDK 1.1
  503. ; // ignore
  504. }
  505. }
  506. if (classLoader == null) {
  507. classLoader = SimpleLog.class.getClassLoader();
  508. }
  509. // Return the selected class loader
  510. return classLoader;
  511. }
  512. private static InputStream getResourceAsStream(final String name)
  513. {
  514. return (InputStream)AccessController.doPrivileged(
  515. new PrivilegedAction() {
  516. public Object run() {
  517. ClassLoader threadCL = getContextClassLoader();
  518. if (threadCL != null) {
  519. return threadCL.getResourceAsStream(name);
  520. } else {
  521. return ClassLoader.getSystemResourceAsStream(name);
  522. }
  523. }
  524. });
  525. }
  526. }