1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.oodt.commons.io;
18
19
20 import java.io.IOException;
21 import java.io.OutputStream;
22 import java.nio.CharBuffer;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25
26
27
28
29
30
31 public class LoggerOutputStream extends OutputStream {
32
33 public static final String NUM_BYTES_PER_WRITE_PROPERTY =
34 "org.apache.oodt.commons.io.logger.os.bytes.per.write";
35 private static final int NUM_BYTES_PER_WRITE = Integer.getInteger(
36 NUM_BYTES_PER_WRITE_PROPERTY, 512);
37
38 private Logger logger;
39 private CharBuffer buffer;
40 private Level logLevel;
41
42 public LoggerOutputStream(Logger logger) throws InstantiationException {
43 this(logger, Level.INFO);
44 }
45
46 public LoggerOutputStream(Logger logger, Level logLevel)
47 throws InstantiationException {
48 this(logger, NUM_BYTES_PER_WRITE, logLevel);
49 }
50
51 public LoggerOutputStream(Logger logger, int numOfBytesPerWrite)
52 throws InstantiationException {
53 this(logger, numOfBytesPerWrite, Level.INFO);
54 }
55
56 public LoggerOutputStream(Logger logger, int numOfBytesPerWrite,
57 Level logLevel) throws InstantiationException {
58 this.logger = logger;
59 this.buffer = CharBuffer.wrap(new char[numOfBytesPerWrite]);
60 this.logLevel = logLevel;
61 }
62
63 @Override
64 public void write(int b) throws IOException {
65 if (!buffer.hasRemaining()) {
66 flush();
67 }
68 buffer.put((char) b);
69 }
70
71 @Override
72 public void flush() {
73 if (buffer.position() > 0) {
74 char[] flushContext = new char[buffer.position()];
75 System.arraycopy(buffer.array(), 0, flushContext, 0, buffer.position());
76 logger.log(logLevel, new String(flushContext));
77 buffer.clear();
78 }
79 }
80
81 @Override
82 public void close() throws IOException {
83 flush();
84 super.close();
85 }
86 }