Created
April 18, 2019 00:15
-
-
Save seraphy/aa32a4226f552b14db7d0b80a342eeb9 to your computer and use it in GitHub Desktop.
標準出力に差し替え可能なプリントストリームを作成し、System.outをログに転送する実装例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void redirectLogs() { | |
// 標準出力・標準エラー出力のログへの転送 | |
Logger stdoutLog = LoggerFactory.getLogger("console.out"); | |
Logger stderrLog = LoggerFactory.getLogger("console.err"); | |
System.setOut(createLogStream(stdoutLog::info)); | |
System.setErr(createLogStream(stderrLog::info)); | |
} | |
/** | |
* 標準出力に差し替え可能なプリントストリームを作成します.<br> | |
* プリントストリームへの出力は文字列として引数のコンシューマに渡されます.<br> | |
* スレッドごとに独立したバッファをもっています. | |
* @return プリントストリーム | |
*/ | |
public static PrintStream createLogStream(Consumer<String> logReceiver) { | |
return new PrintStream(new OutputStream() { | |
private ThreadLocal<ByteArrayOutputStream> bosTls = new ThreadLocal<ByteArrayOutputStream>() { | |
@Override | |
protected ByteArrayOutputStream initialValue() { | |
return new ByteArrayOutputStream(); | |
} | |
}; | |
@Override | |
public void write(int b) throws IOException { | |
if (b == 0x0a || b == 0x0d) { | |
flush(); | |
} else { | |
bosTls.get().write(b); | |
} | |
} | |
@Override | |
public void write(byte[] b, int off, int len) throws IOException { | |
ByteArrayOutputStream bos = bosTls.get(); | |
for (int idx = 0; idx < len; idx++) { | |
byte c = b[off + idx]; | |
if (c == 0x0a || c == 0x0d) { | |
flush(); | |
} else { | |
bos.write(c); | |
} | |
} | |
} | |
@Override | |
public void close() throws IOException { | |
flush(); | |
} | |
@Override | |
public void flush() throws IOException { | |
ByteArrayOutputStream bos = bosTls.get(); | |
if (bos.size() > 0) { | |
String msg = new String(bos.toByteArray()); | |
bos.reset(); | |
logReceiver.accept(msg); | |
} | |
} | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment