以编程方式关闭特定包的java.util.logging [英] Turn off java.util.logging for a specific package programmatically

查看:232
本文介绍了以编程方式关闭特定包的java.util.logging的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用内部使用 Apache CXF 的SDK。 Apache CXF默认使用 java.util.logging 包进行日志记录。

I am using an SDK that uses Apache CXF internally. Apache CXF uses the java.util.logging package for logging by default.

我想更改日志记录级别从 INFO 警告或完全关闭它。我可以在我的应用程序的主方法中以编程方式执行此操作吗?

I want to change the logging level from INFO to WARNING or turn it off completely. Can I do this programmatically in the main method of my application?

推荐答案

有一种方法可以以编程方式执行此操作,但它不是直观。如果你最终需要更精细的控制或多个类控制,那么更改为SLF4J或Log4J可能会更好

There is a way to do this programatically, but it's not intuitive. Changing to SLF4J or Log4J may be better if you end up needing control at a a finer level or over multiple classes

问题是Logger是使用WeakReferences缓存的。从您调用 Logger.setLevel()开始直到实际使用Logger为止,它可能是GC。因此,记录的记录器不是您设置级别的记录器!在启动时有大量GC的框架中尤其如此。

The issue is that Loggers are cached using WeakReferences. From the time you call Logger.setLevel() until the Logger is actually used, it may be GC'ed. So, the Logger that logs isn't the Logger you set the level on! This is especially true in frameworks where there is a lot of GC at startup.

解决方案是以编程方式设置配置,而不是实际记录器。

The solution is to programatically set the configuration, not the actual Loggers.

String logConfig = ".level=" + java.util.logging.Level.INFO + '\n';
logConfig += "handlers=java.util.logging.ConsoleHandler\n";
// ensure ConsoleHandler does not filter
logConfig += "java.util.logging.ConsoleHandler" + ".level=" + java.util.logging.Level.FINEST + '\n';

//set your custom levels
logConfig += "org.apache.cxf" + ".level=" + java.util.logging.Level.WARNING + "\n";

try {
  java.util.logging.LogManager.getLogManager().readConfiguration(new java.io.ByteArrayInputStream(logConfig.getBytes("UTF-8")));
  // no need to close ByteArrayInputStream -- it is a no-op
}
catch (IOException ioe) {
  System.err.println("cannot fully configure logging");
  ioe.printStackTrace();
}

注意这种方法存在一些问题:

Note there are a few issues with this approach:


  1. 您正在覆盖内置配置,因此您必须设置根处理程序。如果你设置 -Djava.util.logging.config.file ,它也会被覆盖。

  2. 总黑客 - 可能不是以后可以维护或理解。

  3. 您的配置字符串必须有效。请注意,所有行都必须以 \ n 结尾。

  4. 必须尽早调用,最好是<$ c中的第一行$ C> main()的。如果无法做到这一点,您可能还需要迭代所有现有的Logger并使用 setLevel()更新其配置。

  1. You are overwriting the built-in configuration, so you have to set the root handler. If you set -Djava.util.logging.config.file, it will also be overwritten.
  2. Total hack - might not be maintainable or understandable later.
  3. Your config string has to be valid. Note all lines have to end with \n.
  4. Has to be called very early, preferably the first line in main(). If this is not possible, you may also need to iterate all the existing Loggers and update their config using setLevel() too.

这篇关于以编程方式关闭特定包的java.util.logging的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆