tags:

views:

2742

answers:

6

I'm using the standard logger from java.util.logging and by default the console output is directed to the error stream (i.e. same as System.err.println). How do I change the console output to the output stream (i.e. same as System.out.println)

A: 

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.

Jon Skeet
I think ConsoleHandler is the default, there is a StreamHandler that can print to any other stream.
Uri
Yes, but you'd want to subclass StreamHandler so as to avoid trying to close System.err, I suspect.
Jon Skeet
A: 

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.

Uri
+4  A: 

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

setUseParentHandlers(false);

Then subclass ConsoleHandler and in the constructor:

setOutputStream(System.out);

Obediah Stane
A: 

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

A: 

Simply extend StreamHandler & in the constructor call Super(System.out,). This will avoid closing System.err - Thanks

Hema
A: 

Handler consoleHandler = new Handler(){

            @Override
            public void publish(LogRecord record)
            {
                if (getFormatter() == null)
                {
                    setFormatter(new SimpleFormatter());
                }

                try {
                    String message = getFormatter().format(record);
                    if (record.getLevel().intValue() >= Level.WARNING.intValue())
                    {
                        System.err.write(message.getBytes());                       
                    }
                    else
                    {
                        System.out.write(message.getBytes());
                    }
                } catch (Exception exception) {
                    reportError(null, exception, ErrorManager.FORMAT_FAILURE);
                    return;
                }

            }

            @Override
            public void close() throws SecurityException {}
            @Override
            public void flush(){}
        };
Jeremiah Jahn