Intercepting and parsing Logger or console output without disturbing it
-
24-06-2021 - |
Question
I am having some trouble with Java. What I want is pretty simple, I am developing a plugin for a mod of a well-known game, Minecraft, and I need to be able to parse every line of console output that comes through to STOUT.
I've looked around on the internet but I can't seem to find anything I can use to do this. I know that some console output is through the default Logger, and some is through system.out. I have a function, parseConsole(String line)
that will parse the line and do something if it contains a word, etc etc. I want this function to be called for every line of output displayed on the console, but it must not interrupt the flow, as in every line will still be sent to the console after being parsed by my function.
Solution
you can use System.setOut() to replace the console PrintStream. you can replace this with an implementation which inspects the text on its way to the console.
here is an example of how you might filter:
public class MyFilterPrintStream extends PrintStream {
@Override public void print(String s) {
// ... process output string here ...
// pass along to actual console output
super.print(s);
}
}
// install my filter
System.setOut(new MyFilterPrintStream(System.out));