All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jidefx.utils.LoggerUtils Maven / Gradle / Ivy

There is a newer version: 0.9.1-b128
Show newest version
/*
 * @(#)LoggerUtils.java 5/19/2013
 *
 * Copyright 2002 - 2013 JIDE Software Inc. All rights reserved.
 */

package jidefx.utils;

import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

/**
 * Utils to allow enable/disable a Java Logger to print certain level of message to console. This is mainly used for
 * debugging purpose.
 */
public class LoggerUtils {
    public static Handler enableLogger(String loggerName, Level level) {
        Logger log = Logger.getLogger(loggerName);
        log.setLevel(level);
        Handler handler = new Handler() {
            @SuppressWarnings({"UseOfSystemOutOrSystemErr"})
            @Override
            public void publish(LogRecord record) {
                System.err.print(record.getMessage());
                Object[] params = record.getParameters();
                if (params != null) {
                    if (params.length > 0)
                        System.err.print("= ");
                    for (int i = 0; i < params.length; i++) {
                        System.err.print(params[i]);
                        if (i < params.length - 1)
                            System.err.print(", ");
                    }
                }
                System.err.println();
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() throws SecurityException {
            }
        };
        log.addHandler(handler);
        return handler;
    }

    public static void disableLogger(String loggerName, Handler handler) {
        Logger log = Logger.getLogger(loggerName);
        log.setLevel(null);
        log.removeHandler(handler);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy