How do I change java logging console output from s

2019-01-14 10:54发布

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)?

标签: java logging
12条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-14 11:18

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.

查看更多
爷的心禁止访问
3楼-- · 2019-01-14 11:18

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.

查看更多
趁早两清
4楼-- · 2019-01-14 11:19

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!

查看更多
疯言疯语
5楼-- · 2019-01-14 11:25

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

查看更多
狗以群分
6楼-- · 2019-01-14 11:27

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.

查看更多
来,给爷笑一个
7楼-- · 2019-01-14 11:31

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

查看更多
登录 后发表回答