001 package org.apache.ojb.broker.util.logging;
002
003 /* Copyright 2002-2005 The Apache Software Foundation
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018 import org.apache.commons.lang.SystemUtils;
019 import org.apache.commons.lang.exception.ExceptionUtils;
020
021 /**
022 * This class is a {@link Logger} implementation based on a {@link StringBuffer}. All
023 * logging method calls are written in the buffer. With method {@link #flushLogBuffer()}
024 * the buffer will be cleared and the buffered log statements returned as string.
025 *
026 * @version $Id: StringBufferLoggerImpl.java,v 1.1 2007-08-24 22:17:32 ewestfal Exp $
027 */
028 public class StringBufferLoggerImpl extends PoorMansLoggerImpl
029 {
030 protected String EOL = SystemUtils.LINE_SEPARATOR;
031 private StringBuffer buffer;
032 private boolean errorLog;
033
034 public StringBufferLoggerImpl(String name)
035 {
036 super(name);
037 buffer = new StringBuffer(1000);
038 }
039
040 /**
041 * Log all statements in a {@link StringBuffer}.
042 */
043 protected void log(String aLevel, Object obj, Throwable t)
044 {
045 buffer.append(BRAKE_OPEN).append(getName()).append(BRAKE_CLOSE).append(aLevel);
046 if (obj != null && obj instanceof Throwable)
047 {
048 try
049 {
050 buffer.append(((Throwable) obj).getMessage()).append(EOL);
051 ((Throwable) obj).printStackTrace();
052 }
053 catch (Throwable ignored)
054 {
055 /*logging should be failsafe*/
056 }
057 }
058 else
059 {
060 try
061 {
062 buffer.append(obj).append(EOL);
063 }
064 catch(Exception e)
065 {
066 // ignore
067 }
068 }
069
070 if (t != null)
071 {
072 try
073 {
074 buffer.append(t.getMessage()).append(EOL);
075 buffer.append(ExceptionUtils.getFullStackTrace(t)).append(EOL);
076 }
077 catch (Throwable ignored)
078 {
079 /*logging should be failsafe*/
080 }
081 }
082 if(!errorLog && (aLevel.equals(STR_ERROR) || aLevel.equals(STR_FATAL)))
083 {
084 errorLog = true;
085 }
086 }
087
088 /**
089 * Returns <em>true</em> if one or more error/fatal log method calls
090 * have been logged in the buffer.
091 */
092 public boolean isErrorLog()
093 {
094 return errorLog;
095 }
096
097 /**
098 * Returns all buffered log statements as string and clear the buffer.
099 */
100 public String flushLogBuffer()
101 {
102 String result = buffer.toString();
103 buffer = new StringBuffer(1000);
104 return result;
105 }
106 }