我有以下代码,我们没有使用 System.out.println 语句,但必须使用记录器打印到控制台。
这里是示例代码(Java):
public void printColumnStats() {
java.util.logging.Logger log = java.util.logging.Logger
.getLogger("ProfileStatusClass");
log.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new MyFormatter());
handler.setLevel(Level.ALL);
log.addHandler(handler);
// This will print the current Column Profiling stats
log.fine("FieldName : " + this.datasetFieldName);
log.fine("Field index : " + this.fieldIndex);
NumberFormat formatter = new DecimalFormat("#0.00000000");
if (this.fieldType.equalsIgnoreCase("number")) {
log.fine("Field Null Count : " + this.datasetFieldNullCount);
log.fine("Field Valid/Obs Count : " + this.datasetFieldObsCount);
log.fine("Field Min : " + (0l + this.datasetFieldMin));
...
我有以下要求(抱歉,这部分是在 Scala 中,但应该很简单:
for (e <- tResults) {
e._2.printColumnStats()
println("++........................................................++")
}
在下一组统计数据拉出之前我得到了大量的重复,即使循环中每种类型只有一个:
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
Field Null Count : 0.0
最佳答案
您将在每次调用“printColumnStats”时添加一个新的 ConsoleHandler。您只想安装一个处理程序。如果您要使用代码来设置记录器,则将设置代码从 printColumnStats 函数中移出并放入静态 block 中。
private static final Logger log = Logger.getLogger("ProfileStatusClass");
static {
log.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new MyFormatter());
handler.setLevel(Level.ALL);
log.addHandler(handler);
}
默认情况下,JVM 也会在根记录器上安装 ConsoleHandler。您的记录器应将 UserParentHandlers 设置为 false,这样您就不会发布到该处理程序。
关于Java Logger 向控制台生成多个相同的日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35025062/