1 16 17 18 import java.io.*; 19 import org.apache.log4j.*; 20 21 22 39 public class LoggingOutputStream extends OutputStream { 40 protected static final String LINE_SEPERATOR = System.getProperty("line.separator"); 41 42 43 46 protected boolean hasBeenClosed = false; 47 48 51 protected byte[] buf; 52 53 59 protected int count; 60 61 62 65 private int bufLength; 66 67 70 public static final int DEFAULT_BUFFER_LENGTH = 2048; 71 72 73 76 protected Category category; 77 78 81 protected Priority priority; 82 83 84 private LoggingOutputStream() { 85 } 87 88 89 99 public LoggingOutputStream(Category cat, Priority priority) 100 throws IllegalArgumentException { 101 if (cat == null) { 102 throw new IllegalArgumentException ("cat == null"); 103 } 104 if (priority == null) { 105 throw new IllegalArgumentException ("priority == null"); 106 } 107 108 this.priority = priority; 109 category = cat; 110 bufLength = DEFAULT_BUFFER_LENGTH; 111 buf = new byte[DEFAULT_BUFFER_LENGTH]; 112 count = 0; 113 } 114 115 116 122 public void close() { 123 flush(); 124 hasBeenClosed = true; 125 } 126 127 128 142 public void write(final int b) throws IOException { 143 if (hasBeenClosed) { 144 throw new IOException("The stream has been closed."); 145 } 146 147 if (b == 0) { 149 return; 150 } 151 152 if (count == bufLength) { 154 final int newBufLength = bufLength+DEFAULT_BUFFER_LENGTH; 156 final byte[] newBuf = new byte[newBufLength]; 157 158 System.arraycopy(buf, 0, newBuf, 0, bufLength); 159 160 buf = newBuf; 161 bufLength = newBufLength; 162 } 163 164 buf[count] = (byte)b; 165 count++; 166 } 167 168 169 177 public void flush() { 178 if (count == 0) { 179 return; 180 } 181 182 if (count == LINE_SEPERATOR.length()) { 184 if ( ((char)buf[0]) == LINE_SEPERATOR.charAt(0) && 185 ( ( count == 1 ) || ( (count == 2) && ((char)buf[1]) == LINE_SEPERATOR.charAt(1) ) ) ) { 187 reset(); 188 return; 189 } 190 } 191 192 final byte[] theBytes = new byte[count]; 193 194 System.arraycopy(buf, 0, theBytes, 0, count); 195 196 category.log(priority, new String (theBytes)); 197 198 reset(); 199 } 200 201 202 private void reset() { 203 count = 0; 206 } 207 208 } 209 210 | Popular Tags |