I\'m using the standard ConsoleHandler
from java.util.logging
and by default the console output is directed to the error stream (i.e. System.
If you set setUseParentHandlers(false); only THAT class has it set. Other classes in the app will still pass it thru to stderr.
The ConsoleHandler will grab a snapshot of System.err
during construction. One option would be to swap the global error stream with the global out stream and then create the ConsoleHandler.
ConsoleHandler h = null;
final PrintStream err = System.err;
System.setErr(System.out);
try {
h = new ConsoleHandler(); //Snapshot of System.err
} finally {
System.setErr(err);
}
This assumes that the code has permission to modify error stream and that no other running code is accessing the error stream. In short, this is an option but there are safer alternatives.
If you use Java logging, you can change the default handler:
For example, for files: Handler fh = new FileHandler(FILENAME); Logger.getLogger(LOGGER_NAME).addHandler(fh);
If you want to output to a stream you can use StreamHandler, I think you can configure it with any output stream that you woud like, including the system stream.
Hmm I just got bit in the foot a few times, trying to accomplish this feat. Before googling my way here I managed to conjure the following hack. Ugly, but it seems to get the job done.
public class StdoutConsoleHandler extends ConsoleHandler {
protected void setOutputStream(OutputStream out) throws SecurityException {
super.setOutputStream(System.out); // kitten killed here :-(
}
}
Watch out: Calling setOutputStream() from the constructor is tempting, but it does (as Jon Skeet already pointed out) close System.err. Mad skills!
I've arrived at
SimpleFormatter fmt = new SimpleFormatter();
StreamHandler sh = new StreamHandler(System.out, fmt);
logger.addHandler(sh);
When we create a new ConsoleHandler object, default output stream is "system.err". Sadly Java doesn't provide any public method for ConsoleHandler class to set output stream. So it can be set only at the time of object creation. As ConsoleHandler class extends StreamHandler, which has a protected method "setOutputStream" to set output stream explicitly. To set output Stream for ConsoleHandler just override this method at the time of new call for object creation.
ConsoleHandler consoleHandler = new ConsoleHandler (){
@Override
protected synchronized void setOutputStream(OutputStream out) throws SecurityException {
super.setOutputStream(System.out);
}
};