Redirect System.out.println to log

前端 未结 5 1312
孤城傲影
孤城傲影 2021-01-11 15:51

In my project test suite there is big usage of

System.out.println 

I\'m trying to redirect these output to log file (through configuration

5条回答
  •  执念已碎
    2021-01-11 16:40

    public class RecursiveLogging {
    public static void main(String[] args) {
        System.setOut(new PrintStream(new CustomOutputStream()));
    
        TestMyException.testPrint();
    }
    
    }
    
    class CustomOutputStream extends OutputStream {
    private Logger logger = Logger.getLogger(this.getClass());
    
    @Override
    public final void write(int b) throws IOException {
        // the correct way of doing this would be using a buffer
        // to store characters until a newline is encountered,
        // this implementation is for illustration only
        logger.info((char) b);
    }
    
    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if ((off < 0) || (off > b.length) || (len < 0) ||
                   ((off + len) > b.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return;
        }
        byte[] pb = new byte[len];
        for (int i = 0 ; i < len ; i++) {
            pb[i] = (b[off + i]);
        }
        String str = new String(pb);
        logger.info(str);
    }
    }
    

提交回复
热议问题