1 package org.oddjob.logging; 2 3 import java.io.ByteArrayOutputStream ; 4 import java.io.IOException ; 5 import java.io.OutputStream ; 6 7 12 public class LoggingOutputStream extends OutputStream { 13 14 private final LogLevel level; 15 16 private final LogArchive consoleArchiver; 17 private ByteArrayOutputStream buffer; 18 19 private final OutputStream existing; 20 21 public LoggingOutputStream(OutputStream existing, LogLevel level, 22 LogArchive consoleArchiver) { 23 this.buffer = new ByteArrayOutputStream (); 24 this.level = level; 25 this.existing = existing; 26 this.consoleArchiver = consoleArchiver; 27 28 } 29 30 public void write(int c) throws IOException { 31 add(c); 32 if (existing != null) existing.write(c); 33 } 34 35 public void write(byte[] b) throws IOException { 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 { 41 add(buf, off, len); 42 if (existing != null) existing.write(buf, off, len); 43 } 44 public void close() throws IOException { 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 (); 73 } 74 } 75 } | Popular Tags |