How do I change java logging console output from std err to std out?

Viewed 45074

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.err).

How do I change the console output to the output stream (i.e. System.out)?

13 Answers

I've arrived at

 SimpleFormatter fmt = new SimpleFormatter();
 StreamHandler sh = new StreamHandler(System.out, fmt);
 logger.addHandler(sh);

I figured out one way. First remove the default console handler:

setUseParentHandlers(false);

Then subclass ConsoleHandler and in the constructor:

setOutputStream(System.out);

Step 1: Set parent handlers to false.

log.setUseParentHandlers(false);

Step 2: Add a handler that writes to System.out

log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));

Thats it..

import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;

public class App {

     static final Logger log = Logger.getLogger("com.sample.app.App");

     static void processData() {
          log.info("Started Processing Data");
          log.info("Finished processing data");
     }

     public static void main(String args[]) throws IOException {
          log.setUseParentHandlers(false);

          log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));

          processData();
     }
}

Have a look at the docs and source for ConsoleHandler - I'm sure you could easily write a version which just uses System.err instead of System.out. (It's a shame that ConsoleHandler doesn't allow this to be configured, to be honest.)

Then it's just a case of configuring the logging system to use your new StdoutHandler (or whatever you call it) in the normal way.

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.

If you set setUseParentHandlers(false); only THAT class has it set. Other classes in the app will still pass it thru to stderr.

Related