View Javadoc
1   package com.randomnoun.common.log4j2;
2   
3   import java.io.IOException;
4   import java.io.InputStreamReader;
5   import java.io.OutputStream;
6   import java.io.PipedInputStream;
7   import java.io.PipedOutputStream;
8   import java.nio.charset.Charset;
9   
10  import org.apache.logging.log4j.Logger;
11  
12  /** An outputstream that writes to a log4j Logger.
13   * 
14   * Lines are terminated by CRLF or LF. 
15   *
16   * @author knoxg
17   */
18  public class LoggingOutputStream extends OutputStream {
19  	Logger logger;
20  	StringBuffer line = new StringBuffer();
21  	PipedOutputStream pos;
22  	PipedInputStream pis;
23  	InputStreamReader isr;
24  	boolean wasCr; // last character was a CR (to convert CRLFs)
25  	
26  	public LoggingOutputStream(Logger logger, Charset charset) throws IOException {
27  		this.logger = logger;
28  		this.pos = new PipedOutputStream();
29  		this.pis = new PipedInputStream(pos);
30  		this.isr = new InputStreamReader(pis, charset);
31  	}
32  	public LoggingOutputStream(Logger logger, String charsetName) throws IOException {
33  		this(logger, Charset.forName(charsetName));
34  	}
35  	public LoggingOutputStream(Logger logger) throws IOException {
36  		this(logger, Charset.defaultCharset());
37  	}
38  	
39  	@Override
40  	public void write(int b) throws IOException {
41  		pos.write(b);
42  		int ch = isr.read();
43  		if (ch == -1) {
44  			// EOF
45  		} else if (ch == 13) { // \r
46  			logger.info(line); line.setLength(0);
47  			wasCr = true;
48  		} else if (ch == 10) { // \n
49  			if (!wasCr) {
50  				logger.info(line); line.setLength(0);
51  			}
52  			wasCr = false;
53  		} else { 
54  			line.append((char) b);
55  			wasCr = false;
56  		}
57  	}
58  }