有没有办法禁用 java.util.logging 并稍后再启用它?

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

我正在使用一个记录了一堆我不想记录的东西的库。它正在使用 java.util.logging

我也不想完全禁用它的日志记录,因为它的一些日志很有用。由于仅当我 运行 执行特定任务时才记录不需要的行,如果有禁用和启用日志记录的全局方法,它将解决我的问题。

最好是这样的:

disableLogging();
taskThatMakesUnnecessaryLogs();
enableLogging();

对于全局影响,您可以使用 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 应该改用。

如果您知道记录器名称,您可以编辑您的 logging.properties 以修改该违规记录器的级别或创建一个 filter.

从代码中您可以找到记录器并将其级别更改为 OFF 或比您看到的日志消息更高的级别。

final Logger chatty = Logger.getLogger("somelogger");
final Level oldLevel = chatty.getLevel();
chatty.setLevel(Level.OFF);
try {
  taskThatMakesUnnecessaryLogs();
} finally {
  chatty.setLevel(oldLevel);
}