001package com.randomnoun.common.log4j2; 002 003import java.io.IOException; 004import java.io.InputStreamReader; 005import java.io.OutputStream; 006import java.io.PipedInputStream; 007import java.io.PipedOutputStream; 008import java.nio.charset.Charset; 009 010import org.apache.logging.log4j.Logger; 011 012/** An outputstream that writes to a log4j Logger. 013 * 014 * Lines are terminated by CRLF or LF. 015 * 016 * @author knoxg 017 */ 018public class LoggingOutputStream extends OutputStream { 019 Logger logger; 020 StringBuffer line = new StringBuffer(); 021 PipedOutputStream pos; 022 PipedInputStream pis; 023 InputStreamReader isr; 024 boolean wasCr; // last character was a CR (to convert CRLFs) 025 026 public LoggingOutputStream(Logger logger, Charset charset) throws IOException { 027 this.logger = logger; 028 this.pos = new PipedOutputStream(); 029 this.pis = new PipedInputStream(pos); 030 this.isr = new InputStreamReader(pis, charset); 031 } 032 public LoggingOutputStream(Logger logger, String charsetName) throws IOException { 033 this(logger, Charset.forName(charsetName)); 034 } 035 public LoggingOutputStream(Logger logger) throws IOException { 036 this(logger, Charset.defaultCharset()); 037 } 038 039 @Override 040 public void write(int b) throws IOException { 041 pos.write(b); 042 int ch = isr.read(); 043 if (ch == -1) { 044 // EOF 045 } else if (ch == 13) { // \r 046 logger.info(line); line.setLength(0); 047 wasCr = true; 048 } else if (ch == 10) { // \n 049 if (!wasCr) { 050 logger.info(line); line.setLength(0); 051 } 052 wasCr = false; 053 } else { 054 line.append((char) b); 055 wasCr = false; 056 } 057 } 058}