01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */
19: package org.apache.openjpa.lib.log;
20:
21: import java.io.ByteArrayOutputStream;
22: import java.io.IOException;
23: import java.io.OutputStream;
24: import java.util.StringTokenizer;
25:
26: import org.apache.openjpa.lib.util.J2DoPrivHelper;
27:
28: /**
29: * Many standard components log to {@link OutputStream}s.
30: * This wrapper class extends the {@link ByteArrayOutputStream}
31: * class and writes all given data to an underlying {@link Log} instance
32: * whenever it is flushed and the internally held byte array contains a newline.
33: *
34: * @author Abe White, Marc Prud'hommeaux
35: */
36: public class LogOutputStream extends ByteArrayOutputStream {
37:
38: private static final String _sep = J2DoPrivHelper
39: .getLineSeparator();
40:
41: private final int _level;
42: private final Log _log;
43:
44: /**
45: * Constructor.
46: *
47: * @param log the log to log to
48: * @param level the level to log at
49: */
50: public LogOutputStream(Log log, int level) {
51: _log = log;
52: _level = level;
53: }
54:
55: public void flush() throws IOException {
56: super .flush();
57: byte[] bytes = toByteArray();
58: if (bytes.length == 0)
59: return;
60:
61: String msg = new String(bytes);
62: if (msg.indexOf(_sep) != -1) {
63: // break up the message based on the line separator; this
64: // may be because the flushed buffer contains mutliple lines
65: for (StringTokenizer tok = new StringTokenizer(msg, _sep); tok
66: .hasMoreTokens();) {
67: String next = tok.nextToken();
68: log(next);
69: }
70:
71: // clear the internally held byte array
72: reset();
73: }
74: }
75:
76: private void log(String msg) {
77: switch (_level) {
78: case Log.TRACE:
79: _log.trace(msg);
80: break;
81: case Log.INFO:
82: _log.info(msg);
83: break;
84: case Log.WARN:
85: _log.warn(msg);
86: break;
87: case Log.ERROR:
88: _log.error(msg);
89: break;
90: case Log.FATAL:
91: _log.fatal(msg);
92: break;
93: }
94: }
95: }
|