01: package org.apache.ojb.broker.util.logging;
02:
03: /* Copyright 2002-2005 The Apache Software Foundation
04: *
05: * Licensed under the Apache License, Version 2.0 (the "License");
06: * you may not use this file except in compliance with the License.
07: * You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: import org.apache.commons.lang.SystemUtils;
19: import org.apache.commons.lang.exception.ExceptionUtils;
20:
21: /**
22: * This class is a {@link Logger} implementation based on a {@link StringBuffer}. All
23: * logging method calls are written in the buffer. With method {@link #flushLogBuffer()}
24: * the buffer will be cleared and the buffered log statements returned as string.
25: *
26: * @version $Id: StringBufferLoggerImpl.java,v 1.1.2.2 2005/12/21 22:28:16 tomdz Exp $
27: */
28: public class StringBufferLoggerImpl extends PoorMansLoggerImpl {
29: protected String EOL = SystemUtils.LINE_SEPARATOR;
30: private StringBuffer buffer;
31: private boolean errorLog;
32:
33: public StringBufferLoggerImpl(String name) {
34: super (name);
35: buffer = new StringBuffer(1000);
36: }
37:
38: /**
39: * Log all statements in a {@link StringBuffer}.
40: */
41: protected void log(String aLevel, Object obj, Throwable t) {
42: buffer.append(BRAKE_OPEN).append(getName()).append(BRAKE_CLOSE)
43: .append(aLevel);
44: if (obj != null && obj instanceof Throwable) {
45: try {
46: buffer.append(((Throwable) obj).getMessage()).append(
47: EOL);
48: ((Throwable) obj).printStackTrace();
49: } catch (Throwable ignored) {
50: /*logging should be failsafe*/
51: }
52: } else {
53: try {
54: buffer.append(obj).append(EOL);
55: } catch (Exception e) {
56: // ignore
57: }
58: }
59:
60: if (t != null) {
61: try {
62: buffer.append(t.getMessage()).append(EOL);
63: buffer.append(ExceptionUtils.getFullStackTrace(t))
64: .append(EOL);
65: } catch (Throwable ignored) {
66: /*logging should be failsafe*/
67: }
68: }
69: if (!errorLog
70: && (aLevel.equals(STR_ERROR) || aLevel
71: .equals(STR_FATAL))) {
72: errorLog = true;
73: }
74: }
75:
76: /**
77: * Returns <em>true</em> if one or more error/fatal log method calls
78: * have been logged in the buffer.
79: */
80: public boolean isErrorLog() {
81: return errorLog;
82: }
83:
84: /**
85: * Returns all buffered log statements as string and clear the buffer.
86: */
87: public String flushLogBuffer() {
88: String result = buffer.toString();
89: buffer = new StringBuffer(1000);
90: return result;
91: }
92: }
|