简体   繁体   中英

Java Logger Producing Multiple of the Same Log to Console

I have the following code, we are not using System.out.println statements but have to use a logger to print out to console.

Here is example code (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));
...

I have the following call for it (sorry this part is in Scala, but should be straight forward:

 for (e <- tResults) {
        e._2.printColumnStats()
        println("++........................................................++")
      }

What I am getting tons of repeats before the next set of stats pulls up even though there is just one of each type for the loop:

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

You are adding a new ConsoleHandler on every call to 'printColumnStats'. You only want to install one handler. If you are going to use code to setup the logger then move the setup code out of the printColumnStats function and into a static 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);
}

By default, the JVM will install a ConsoleHandler on the root logger too. Your logger should setUserParentHandlers to false so you don't publish to that handler too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM