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();
Sarp
  • 95
  • 1
  • 7
  • Possibly related: https://stackoverflow.com/questions/5270052/how-to-exclude-a-single-class-from-a-log4j-logger-appender – Michael May 25 '18 at 17:01
  • Also possibly related: https://logging.apache.org/log4j/2.0/manual/filters.html – Michael May 25 '18 at 17:02
  • Basically, there are better ways to do what you want to do than what you're proposing. – Michael May 25 '18 at 17:03
  • @Michael name any – Antoniossss May 25 '18 at 17:20
  • You didnt name any. – Antoniossss May 25 '18 at 17:29
  • 1
    @Michael both links you posted have to do with log4j, not util.logging – puhlen May 25 '18 at 17:31
  • Yes you did linked, Iv asked you to name it ;) – Antoniossss May 25 '18 at 17:44
  • @puhlen 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? – Michael May 25 '18 at 17:45
  • @Michael 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.logging – Sarp May 25 '18 at 17:48
  • @Sarp Ah yes, I forgot it was a library. In which case, you can use [an SLF4J bridge](https://www.slf4j.org/legacy.html). – Michael May 25 '18 at 17:52
  • @Michael util.logging is fine. There are many good logging libraries out there, log4j isn't the only option. – puhlen May 25 '18 at 18:19
  • @puhlen 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. – Michael May 25 '18 at 18:27

1 Answers1

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);
}
jmehrens
  • 10,580
  • 1
  • 38
  • 47