简体   繁体   中英

How do I stop a Java library from printing to the console?

I am using a library that prints a bunch of superfluous information to the console when I reference it. Is there a way to silence the output of the library?

If it is using a logging framework (log4j, commons-logging, etc), you can edit/create a properties file to indicate a high logging treshold. in log4j this would look like:

log4j.logger.org.library=error

If the library is using System.out , that's not a good library in the first place. You can change the PrintStream by calling System.setOut(yourDummyPrintStream) (and System.setErr(..) ). Your dummy print stream would just swallow the data and not print it anywhere.

您是否尝试使用System.setOut()System.setErr()设置OUT-和ERR通道?

I voted up Jan's answer and wanted to add:

Using setOut means that you can't print to system.out in your program any more.

You can do

PrintStream oldOut=System.out

first to save it, then call setOut to change it--then just print to oldOut.

I've gone so far as to use this as a mini-logger--grab the System.out, replace it with my own stream and have my own stream grab a stack trace and figure out the calling method so it can add the method name before forwarding to the original System.out.

Terribly slow, but good for debugging. Had a setting so you could revert to just printing the string, hide all output or filter by which method the message was coming from (which was my main usage, hiding all the other garbage so I could see my own output).

Consider using AspectJ, which can replace all occurrences of System.out.println() with a statement of your choice, a log statement propably. This also works with 3rd party jar files (look for load-time weaving).

I don't think any decent/sane library uses System.out to log the messages. So I can safely assume that its using some kind of logging framework. Configure that the particular package to be at a higher logging level like 'ERROR' or 'FATAL' so that you won't see those messages.

The library is likely using a logger, log4j or slf4j. It is possible that you can create a config file for that logger and then set the log level to WARN or higher. This will stop the info from being printed.

如果lib使用打印,我将使用asm来替换所有sys.out.printXXx,并调用另一个具有类似方法signatutes吞下的类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM