KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > logging > LoggingOutputStream


1 package org.oddjob.logging;
2
3 import java.io.ByteArrayOutputStream JavaDoc;
4 import java.io.IOException JavaDoc;
5 import java.io.OutputStream JavaDoc;
6
7 /**
8  * An output stream that splits output into an existing
9  * output stream if supplied, and a console archive.
10  *
11  */

12 public class LoggingOutputStream extends OutputStream JavaDoc {
13     
14     private final LogLevel level;
15     
16     private final LogArchive consoleArchiver;
17     private ByteArrayOutputStream JavaDoc buffer;
18     
19     private final OutputStream JavaDoc existing;
20     
21     public LoggingOutputStream(OutputStream JavaDoc existing, LogLevel level,
22             LogArchive consoleArchiver) {
23         this.buffer = new ByteArrayOutputStream JavaDoc();
24         this.level = level;
25         this.existing = existing;
26         this.consoleArchiver = consoleArchiver;
27
28     }
29     
30     public void write(int c) throws IOException JavaDoc {
31         add(c);
32         if (existing != null) existing.write(c);
33     }
34     
35     public void write(byte[] b) throws IOException JavaDoc {
36         add(b, 0, b.length);
37         if (existing != null) existing.write(b);
38     }
39     
40     public void write(byte[] buf, int off, int len) throws IOException JavaDoc {
41         add(buf, off, len);
42         if (existing != null) existing.write(buf, off, len);
43     }
44     public void close() throws IOException JavaDoc {
45         next();
46         if (existing != null) existing.close();
47     }
48     
49     void add(byte[] buf, int off , int length) {
50         synchronized (buffer) {
51             for (int i = off; i < length; ++i) {
52                 if (buf[i] == '\n') {
53                     buffer.write(buf, off, i - off + 1);
54                     next();
55                     add(buf, i+1, length - (i - off +1));
56                     return;
57                 }
58             }
59             buffer.write(buf, off, length);
60         }
61     }
62
63     void add(int c) {
64         synchronized (buffer) {
65             buffer.write(c);
66         }
67     }
68         
69     void next() {
70         synchronized (buffer) {
71             consoleArchiver.addEvent(level, buffer.toString());
72             buffer = new ByteArrayOutputStream JavaDoc();
73         }
74     }
75 }
Popular Tags