DefaultLoggerManager.java

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.maven.logging.impl;

import java.io.InputStream;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.maven.api.Constants;
import org.apache.maven.api.logging.LogEvent;
import org.apache.maven.api.logging.LogLevel;
import org.apache.maven.api.logging.LogSink;
import org.apache.maven.api.logging.Logger;
import org.apache.maven.api.logging.LoggerManager;
import org.apache.maven.jline.MessageUtils;

/**
 * Default {@link LoggerManager} implementation. Owns:
 * <ul>
 *   <li>Per-logger level configuration (loaded from properties files)</li>
 *   <li>The active {@link LogSink}</li>
 *   <li>Severity tracking for {@code --fail-on-severity}</li>
 * </ul>
 * <p>
 * This class has no SLF4J dependency. The SLF4J adapter layer creates
 * an instance and registers it via {@link LoggerManager#set(LoggerManager)}.
 *
 * @since 4.2.0
 */
public class DefaultLoggerManager implements LoggerManager {

    private static final String CONFIGURATION_FILE = "maven.logger.properties";

    @Deprecated(since = "4.0.0")
    private static final String LEGACY_CONFIGURATION_FILE = "simplelogger.properties";

    private static final String LEGACY_PREFIX = "org.slf4j.simpleLogger.";

    public static final int LOG_LEVEL_TRACE = 0;
    public static final int LOG_LEVEL_DEBUG = 10;
    public static final int LOG_LEVEL_INFO = 20;
    public static final int LOG_LEVEL_WARN = 30;
    public static final int LOG_LEVEL_ERROR = 40;
    public static final int LOG_LEVEL_OFF = 50;

    private static final AtomicLong SEQUENCE = new AtomicLong();

    private volatile LogSink logSink;
    private volatile int defaultLogLevel = LOG_LEVEL_INFO;
    private final AtomicReference<LogLevel> maxReached = new AtomicReference<>(null);
    private final Properties properties = new Properties();
    private final ConcurrentHashMap<String, Integer> levelCache = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, Logger> loggers = new ConcurrentHashMap<>();
    private final List<Runnable> reconfigurationListeners = new CopyOnWriteArrayList<>();
    private final Map<ClassLoader, String> pluginClassLoaders = Collections.synchronizedMap(new WeakHashMap<>());

    private volatile FormatConfig formatConfig;
    private volatile String[] cachedLevelRenderings;

    public DefaultLoggerManager() {
        this.logSink = new AccumulatingLogSink();
        loadConfiguration();
    }

    // -- LogManager: loggers --

    @Override
    public Logger getLogger(String name) {
        return loggers.computeIfAbsent(name, DefaultLogger::new);
    }

    @Override
    public Logger getLogger(Class<?> clazz) {
        String pluginId = getPluginId(clazz.getClassLoader());
        if (pluginId != null) {
            String key = clazz.getName() + "@" + pluginId;
            return loggers.computeIfAbsent(key, k -> new DefaultLogger(clazz.getName(), null, null, pluginId));
        }
        return getLogger(clazz.getName());
    }

    // -- LogManager: sink --

    @Override
    public LogSink getLogSink() {
        return logSink;
    }

    /**
     * Installs this manager as the global {@link LoggerManager} singleton.
     * Intended for use by embedders and tests.
     *
     * @since 4.2.0
     */
    public void install() {
        LoggerManager.set(this);
    }

    /**
     * Clears the global {@link LoggerManager} singleton if it is currently this instance.
     * Intended for use by tests to restore a clean state after each test method.
     *
     * @since 4.2.0
     */
    public void uninstall() {
        if (LoggerManager.get() == this) {
            LoggerManager.set(null);
        }
    }

    @Override
    public void setLogSink(LogSink sink) {
        LogSink old = this.logSink;
        // Swap BEFORE draining: any concurrent doLog() after this point writes
        // directly to the new sink (no event loss). Replayed bootstrap events
        // arrive after any post-swap live events, but LogEvent.sequenceNumber()
        // provides true ordering for consumers that need it.
        this.logSink = sink;
        if (old != null && sink != null) {
            old.drainTo(sink);
        }
    }

    /**
     * A sink that buffers events until a real sink is installed.
     * Used as the default during early bootstrap.
     * <p>
     * Uses {@link ConcurrentLinkedQueue} with {@code poll()}-based draining to avoid
     * the TOCTOU race inherent in {@code CopyOnWriteArrayList}: iterating a snapshot
     * and then calling {@code clear()} can silently drop events added concurrently
     * between the end of the iteration and the {@code clear()} call.
     */
    private static class AccumulatingLogSink implements LogSink {
        private final ConcurrentLinkedQueue<LogEvent> events = new ConcurrentLinkedQueue<>();

        @Override
        public void accept(LogEvent event) {
            events.add(event);
        }

        @Override
        public void drainTo(LogSink target) {
            LogEvent event;
            while ((event = events.poll()) != null) {
                target.accept(event);
            }
        }
    }

    // -- LogManager: level checking --

    @Override
    public boolean isLevelEnabled(String loggerName, LogLevel level) {
        int configuredLevel = getLoggerLevel(loggerName);
        return toIntLevel(level) >= configuredLevel;
    }

    @Override
    public void setRootLoggerLevel(LogLevel level) {
        String value =
                switch (level) {
                    case TRACE -> "trace";
                    case DEBUG -> "debug";
                    case INFO -> "info";
                    case WARN -> "warn";
                    case ERROR -> "error";
                };
        System.setProperty(Constants.MAVEN_LOGGER_DEFAULT_LOG_LEVEL, value);
        reconfigure();
    }

    @Override
    public void reconfigure() {
        loadConfiguration();
        maxReached.set(null);
        for (Runnable listener : reconfigurationListeners) {
            listener.run();
        }
    }

    /**
     * Registers a listener that is called whenever the logging configuration is reloaded
     * (e.g. when the root log level changes). The SLF4J adapter layer uses this to propagate
     * level changes to already-created SLF4J logger instances.
     *
     * @param listener the callback to invoke on reconfiguration; must not be {@code null}
     */
    public void addReconfigurationListener(Runnable listener) {
        reconfigurationListeners.add(listener);
    }

    // -- LogManager: severity tracking --

    @Override
    public boolean hasReached(LogLevel level) {
        LogLevel reached = maxReached.get();
        return reached != null && reached.ordinal() >= level.ordinal();
    }

    public static long nextSequenceNumber() {
        return SEQUENCE.getAndIncrement();
    }

    public void record(LogLevel level) {
        while (true) {
            LogLevel r = maxReached.get();
            if (r == null || level.ordinal() > r.ordinal()) {
                if (!maxReached.compareAndSet(r, level)) {
                    continue;
                }
            }
            break;
        }
    }

    // -- Plugin classloader registry --

    @Override
    public void registerPluginClassLoader(ClassLoader classLoader, String pluginId) {
        pluginClassLoaders.put(classLoader, pluginId);
    }

    @Override
    public String getPluginId(ClassLoader classLoader) {
        if (classLoader == null) {
            return null;
        }
        return pluginClassLoaders.get(classLoader);
    }

    // -- Line formatting --

    @Override
    public String formatLine(LogEvent event) {
        FormatConfig cfg = this.formatConfig;
        StringBuilder buf = new StringBuilder(80);

        if (cfg.showDateTime) {
            Instant ts = event.timestamp();
            if (ts != null) {
                DateTimeFormatter fmt = cfg.dateTimeFormatter;
                if (fmt != null) {
                    buf.append(fmt.format(ts));
                } else {
                    buf.append(ts.toEpochMilli());
                }
                buf.append(' ');
            }
        }

        if (cfg.showThreadId) {
            buf.append("thread=").append(event.threadId()).append(' ');
        }
        if (cfg.showThreadName) {
            String threadName = event.threadName();
            if (threadName != null) {
                buf.append('[').append(threadName).append("] ");
            }
        }

        if (cfg.levelInBrackets) {
            buf.append('[');
        }
        buf.append(renderLevel(event.level()));
        if (cfg.levelInBrackets) {
            buf.append(']');
        }
        buf.append(' ');

        if (cfg.showLogName) {
            String loggerName = event.loggerName();
            if (loggerName != null) {
                buf.append(loggerName).append(" - ");
            }
        }

        buf.append(event.message());

        return buf.toString();
    }

    private String renderLevel(LogLevel level) {
        String[] cache = cachedLevelRenderings;
        if (cache == null) {
            cache = new String[LogLevel.values().length];
            cache[LogLevel.TRACE.ordinal()] =
                    MessageUtils.builder().trace("TRACE").build();
            cache[LogLevel.DEBUG.ordinal()] =
                    MessageUtils.builder().debug("DEBUG").build();
            cache[LogLevel.INFO.ordinal()] = MessageUtils.builder().info("INFO").build();
            cache[LogLevel.WARN.ordinal()] =
                    MessageUtils.builder().warning("WARNING").build();
            cache[LogLevel.ERROR.ordinal()] =
                    MessageUtils.builder().error("ERROR").build();
            cachedLevelRenderings = cache;
        }
        return cache[level.ordinal()];
    }

    // -- Level resolution --

    /**
     * Returns the effective int log level for a logger name,
     * walking the name hierarchy (e.g. "com.example.Foo" ��� "com.example" ��� "com").
     * Results are cached until {@link #reconfigure()} is called.
     */
    public int getLoggerLevel(String loggerName) {
        if (loggerName != null) {
            return levelCache.computeIfAbsent(loggerName, this::computeLoggerLevel);
        }
        return defaultLogLevel;
    }

    private int computeLoggerLevel(String name) {
        String levelString = recursivelyComputeLevelString(name);
        return levelString != null ? stringToLevel(levelString) : defaultLogLevel;
    }

    public int getDefaultLogLevel() {
        return defaultLogLevel;
    }

    private String recursivelyComputeLevelString(String name) {
        String tempName = name;
        String levelString = null;
        int indexOfLastDot = tempName.length();
        while ((levelString == null) && (indexOfLastDot > -1)) {
            tempName = tempName.substring(0, indexOfLastDot);
            levelString = getStringProperty(Constants.MAVEN_LOGGER_LOG_PREFIX + tempName, null);
            indexOfLastDot = tempName.lastIndexOf(".");
        }
        return levelString;
    }

    // -- Configuration loading --

    private void loadConfiguration() {
        levelCache.clear();
        properties.clear();

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = ClassLoader.getSystemClassLoader();
        }

        try (InputStream in = cl.getResourceAsStream(CONFIGURATION_FILE)) {
            if (in != null) {
                properties.load(in);
            }
        } catch (java.io.IOException e) {
            // ignored
        }

        try (InputStream in = cl.getResourceAsStream(LEGACY_CONFIGURATION_FILE)) {
            if (in != null) {
                Properties legacyProps = new Properties();
                legacyProps.load(in);
                for (String propName : legacyProps.stringPropertyNames()) {
                    String mavenKey = propName.replace(LEGACY_PREFIX, Constants.MAVEN_LOGGER_PREFIX);
                    if (!properties.containsKey(mavenKey)) {
                        properties.setProperty(mavenKey, legacyProps.getProperty(propName));
                    }
                }
            }
        } catch (java.io.IOException e) {
            // ignored
        }

        String defaultLogLevelString = getStringProperty(Constants.MAVEN_LOGGER_DEFAULT_LOG_LEVEL, null);
        if (defaultLogLevelString != null) {
            defaultLogLevel = stringToLevel(defaultLogLevelString);
        } else {
            defaultLogLevel = LOG_LEVEL_INFO;
        }

        boolean showDateTime = getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_DATE_TIME, false);
        DateTimeFormatter dtFormatter = null;
        if (showDateTime) {
            String format = getStringProperty(Constants.MAVEN_LOGGER_DATE_TIME_FORMAT, null);
            if (format != null && !format.isEmpty()) {
                dtFormatter = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault());
            }
        }
        this.formatConfig = new FormatConfig(
                showDateTime,
                dtFormatter,
                getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_THREAD_ID, false),
                getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_THREAD_NAME, false),
                getBooleanProperty(Constants.MAVEN_LOGGER_LEVEL_IN_BRACKETS, false),
                getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_LOG_NAME, false));
        this.cachedLevelRenderings = null;
    }

    // -- Property helpers --

    public String getStringProperty(String name, String defaultValue) {
        String prop = getStringProperty(name);
        return (prop == null) ? defaultValue : prop;
    }

    public boolean getBooleanProperty(String name, boolean defaultValue) {
        String prop = getStringProperty(name);
        return (prop == null) ? defaultValue : "true".equalsIgnoreCase(prop);
    }

    public String getStringProperty(String name) {
        String prop = null;
        try {
            prop = System.getProperty(name);
            if (prop == null && name.startsWith(Constants.MAVEN_LOGGER_PREFIX)) {
                String legacyName = name.replace(Constants.MAVEN_LOGGER_PREFIX, LEGACY_PREFIX);
                prop = System.getProperty(legacyName);
            }
        } catch (SecurityException e) {
            // ignored
        }

        if (prop == null) {
            prop = properties.getProperty(name);
            if (prop == null && name.startsWith(Constants.MAVEN_LOGGER_PREFIX)) {
                String legacyName = name.replace(Constants.MAVEN_LOGGER_PREFIX, LEGACY_PREFIX);
                prop = properties.getProperty(legacyName);
            }
        }
        return prop;
    }

    public static int stringToLevel(String levelStr) {
        if ("trace".equalsIgnoreCase(levelStr)) {
            return LOG_LEVEL_TRACE;
        } else if ("debug".equalsIgnoreCase(levelStr)) {
            return LOG_LEVEL_DEBUG;
        } else if ("info".equalsIgnoreCase(levelStr)) {
            return LOG_LEVEL_INFO;
        } else if ("warn".equalsIgnoreCase(levelStr)) {
            return LOG_LEVEL_WARN;
        } else if ("error".equalsIgnoreCase(levelStr)) {
            return LOG_LEVEL_ERROR;
        } else if ("off".equalsIgnoreCase(levelStr)) {
            return LOG_LEVEL_OFF;
        }
        return LOG_LEVEL_INFO;
    }

    private static final int[] INT_LEVELS = {
        LOG_LEVEL_TRACE, LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, LOG_LEVEL_WARN, LOG_LEVEL_ERROR
    };

    public static int toIntLevel(LogLevel level) {
        return INT_LEVELS[level.ordinal()];
    }

    record FormatConfig(
            boolean showDateTime,
            DateTimeFormatter dateTimeFormatter,
            boolean showThreadId,
            boolean showThreadName,
            boolean levelInBrackets,
            boolean showLogName) {}
}