How to let root and named loggers's filehandler log to the same file?
我的目标是使用java.util.logging(jdk1.6)
- 将所有日志写入同一日志文件,然后
- 做日志旋转
- 可以在文件模式中使用%u以避免与其他程序潜在的文件冲突
我已经配置了一个根记录器和几个命名记录器,其中
使用设置
将根记录程序的处理程序设置为
1 2 3 4 5 | java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter java.util.logging.FileHandler.pattern = xxx.%u.log java.util.logging.FileHandler.limit = 200000 java.util.logging.FileHandler.count = 20 java.util.logging.FileHandler.append = true |
并将命名记录器的处理程序设置为
具有自定义设置
1 2 3 | customFileH.class = java.util.logging.FileHandler customFileH.level = ALL customFileH.formatter = xxxFormat |
当我运行程序时,根记录器会将日志写入xxx.0.log,
命名为logger时,会将日志作为不同的日志文件写入xxx.0.log.1。
即使我以文件模式取出了"%u";备注文件旋转配置,
他们将其写入不同的日志文件了吗? :(
感谢您的任何评论。 :)
好像您正在尝试将log4j样式配置应用于java.util.logging。如果要使用不同的格式化程序创建多个FileHandler,则必须使用config选项安装每个FileHandler。创建一个配置类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package so; import java.io.IOException; import java.util.logging.FileHandler; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.logging.XMLFormatter; public final class LoggingConfig { /** * Pin the loggers. */ private static final Logger root = Logger.getLogger(""); private static final Logger named = Logger.getLogger("some.name"); /** * Configure the loggers. * @throws Exception if there is a problem. */ public LoggingConfig() throws Exception { root.addHandler(newRootHandler()); named.addHandler(newNamedHandler()); } private FileHandler newRootHandler() throws IOException { FileHandler f = new FileHandler("simple%g.%u.log", 200000, 20, true); f.setFormatter(new SimpleFormatter()); return f; } private FileHandler newNamedHandler() throws IOException { FileHandler f = new FileHandler("xml%g.%u.log", 200000, 20, true); f.setFormatter(new XMLFormatter()); return f; } } |
然后将以下内容添加到您的logging.properties:
1 | config=so.LoggingConfig |
否则,您可以将FileHandler子类化,仅创建一个可在logging.properties中使用的新类名。
您必须使用%g选项来区分旋转的日志,并使用%u来处理冲突。从FileHandler文档中:
Thus if three processes were all trying to log to fred%u.%g.txt then they might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as the first file in their rotating sequences.
默认情况下,所有命名记录器都将写入根记录器的处理程序。因此,根据您的工作,您可能不需要将文件处理程序附加到命名记录器。