Is there a way to disable java.util.logging and enable it back later?
Asked Answered
H

1

6

I'm using a library that logs a bunch of stuff that I don't want to log. It's using java.util.logging.

I also don't want to completely disable its logging since some of its logs are useful. Since the unwanted lines are logged only when I run a certain task, if there was a global way of disabling and enabling logging it would solve my problem.

Ideally something like:

disableLogging();
taskThatMakesUnnecessaryLogs();
enableLogging();
Horsecar answered 25/5, 2018 at 16:59 Comment(12)
Possibly related: #5270552Ditto
Also possibly related: logging.apache.org/log4j/2.0/manual/filters.htmlDitto
Basically, there are better ways to do what you want to do than what you're proposing.Ditto
@Ditto name anyGilbertine
You didnt name any.Gilbertine
@Ditto both links you posted have to do with log4j, not util.loggingVaughan
Yes you did linked, Iv asked you to name it ;)Gilbertine
@Vaughan That's why I didn't flag as a duplicate. That's the good way to do it. Sure, you can go for a square-peg-round-hole with util.logging, but why would you?Ditto
@Ditto The library is using util.logging. I could fork the library and change the source code so that it doesn't make the unnecessary logs but that seems worse. So using a different logging framework is out of the question. I know it's not ideal but i need a way of making this work with util.loggingHorsecar
@Horsecar Ah yes, I forgot it was a library. In which case, you can use an SLF4J bridge.Ditto
@Ditto util.logging is fine. There are many good logging libraries out there, log4j isn't the only option.Vaughan
@Vaughan I didn't say j.u.l wasn't fine or that log4j is the only option. I said j.u.l is not suited for this use-case.Ditto
R
7

For a global impact you can use LogManager.reset() as your call to disable logging and to re-enable logging you can LogManager.readConfiguration(). However, there are some major flaws in what actually gets reloaded. The newer JDK9 method LogManager.updateConfiguration should be used instead.

If you know the logger name you can edit your logging.properties to modify the level of that offending logger or create a filter.

From code you can locate the logger and change it's level to OFF or something higher than the log messages you are seeing.

final Logger chatty = Logger.getLogger("somelogger");
final Level oldLevel = chatty.getLevel();
chatty.setLevel(Level.OFF);
try {
  taskThatMakesUnnecessaryLogs();
} finally {
  chatty.setLevel(oldLevel);
}
Rawson answered 25/5, 2018 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.