/*
 * @author Ranides Atterwim {@literal <ranides@gmail.com>}
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.trace;

import lombok.experimental.UtilityClass;
import org.slf4j.LoggerFactory;

/**
 * Utility methods for SLF4J and java.util.logging
 *
 * @author Ranides Atterwim {@literal <ranides@gmail.com>}
 */
@UtilityClass
public class LoggerUtils {

    /**
     * Returns logger for the "current" class, so you don't have to hardcode class name.
     * Can be invoked from static context.
     *
     * @return Logger
     */
    public static org.slf4j.Logger getLogger() {
        return LoggerFactory.getLogger(TraceUtils.getCallerName());
    }

    /**
     * Installs default uncaught exception handler for all threads.
     * Handler will log error message using provided logger.
     *
     * @param logger logger
     */
    public static void setThreadLogger(org.slf4j.Logger logger) {
        Thread.setDefaultUncaughtExceptionHandler((thread, exception) -> {
            logger.error("Abnormal termination of thread: " + thread.getName(), exception);
        });
    }

    /**
     * Resets java.util configuration and changes global logging level.
     * Returns global logger which can be used for additional configuration.
     *
     * @param level level
     * @return logger
     */
    public static java.util.logging.Logger resetJavaLogger(java.util.logging.Level level) {
        java.util.logging.LogManager.getLogManager().reset();
        java.util.logging.Logger global = java.util.logging.Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
        global.setLevel(level);
        return global;
    }

    /**
     * Removes all ConsoleHandlers from provided logger
     *
     * @param logger logger
     */
    public static void removeHandlers(final java.util.logging.Logger logger) {
        for(java.util.logging.Handler handler : logger.getHandlers()) {
            if( handler instanceof java.util.logging.ConsoleHandler) {
                logger.removeHandler(handler);
            }
        }
    }
    
}
