package com.axis.innovators.box;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

/**
 * 将输出传递给 Log4j2 的日志记录器
 * @author tzdwindows 7
 */
public class Log4j2OutputStream extends OutputStream {
    private static final Logger logger = LogManager.getLogger();
    public static final ByteArrayOutputStream systemOutContent = new ByteArrayOutputStream();
    public static final ByteArrayOutputStream systemErrContent = new ByteArrayOutputStream();
    @Override
    public void write(int b) {
        systemOutContent.write(b);
        logger.info(String.valueOf((char) b));
    }

    @Override
    public void write(byte[] b, int off, int len) {
        systemOutContent.write(b, off, len);
        String message = new String(b, off, len).trim();
        logger.info(message);

    }

    /**
     * 重定向 System.out 和 System.err 到 Log4j2
     */
    public static void redirectSystemStreams() {
        System.setOut(new PrintStream(new Log4j2OutputStream(), true));
        System.setErr(new PrintStream(new Log4j2OutputStream(), true));
    }
}