Skip to content

Instantly share code, notes, and snippets.

@martijnvogten
Last active October 30, 2023 04:34
Show Gist options
  • Save martijnvogten/6088904 to your computer and use it in GitHub Desktop.
Save martijnvogten/6088904 to your computer and use it in GitHub Desktop.
Redirect System.out and System.err to an slf4j Logger
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import org.slf4j.Logger;
public class LoggingOutputStream extends OutputStream {
public static void redirectSysOutAndSysErr(Logger logger) {
System.setOut(new PrintStream(new LoggingOutputStream(logger, LogLevel.INFO)));
System.setErr(new PrintStream(new LoggingOutputStream(logger, LogLevel.ERROR)));
}
private final ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
private final Logger logger;
private final LogLevel level;
public enum LogLevel {
TRACE, DEBUG, INFO, WARN, ERROR,
}
public LoggingOutputStream(Logger logger, LogLevel level) {
this.logger = logger;
this.level = level;
}
@Override
public void write(int b) {
if (b == '\n') {
String line = baos.toString();
baos.reset();
switch (level) {
case TRACE:
logger.trace(line);
break;
case DEBUG:
logger.debug(line);
break;
case ERROR:
logger.error(line);
break;
case INFO:
logger.info(line);
break;
case WARN:
logger.warn(line);
break;
}
} else {
baos.write(b);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment