001/*
002 * This is free and unencumbered software released into the public domain.
003 *
004 * Please see https://github.com/binkley/binkley/blob/master/LICENSE.md.
005 */
006
007package hm.binkley.util.logging;
008
009import ch.qos.logback.classic.Level;
010import ch.qos.logback.classic.LoggerContext;
011import ch.qos.logback.classic.util.ContextInitializer;
012import ch.qos.logback.core.joran.spi.JoranException;
013import org.slf4j.Logger;
014
015import javax.annotation.Nonnull;
016
017import static org.slf4j.LoggerFactory.getILoggerFactory;
018
019/**
020 * {@code LoggerUtil} has utility methods for SLF4J loggers.
021 *
022 * @author <a href="mailto:binkley@alumni.rice.edu">B. K. Oxley (binkley)</a>
023 */
024public final class LoggerUtil {
025    private LoggerUtil() {
026    }
027
028    /**
029     * Programatically changes the log <var>level</var> if <var>logger</var> is a logback logger.
030     *
031     * @param logger the logback logger, never missing
032     * @param level the new level, never missing
033     *
034     * @throws ClassCastException if <var>logger</var> is not a logback logger
035     */
036    public static void setLevel(@Nonnull final Logger logger, @Nonnull final Level level) {
037        ((ch.qos.logback.classic.Logger) logger).setLevel(level);
038    }
039
040    /** Resets the global logack, forcing reread of configuration. */
041    public static void refreshLogback() {
042        try {
043            final LoggerContext context = (LoggerContext) getILoggerFactory();
044            context.reset();
045            context.getStatusManager().clear();
046            new ContextInitializer(context).autoConfig();
047        } catch (final JoranException e) {
048            throw new RuntimeException(e);
049        }
050    }
051}