gnodet-bot commented on code in PR #13832:
URL: https://github.com/apache/maven/pull/13832#discussion_r4621248160


##########
impl/maven-logging/src/main/java/org/apache/maven/logging/impl/DefaultLogEvent.java:
##########
@@ -0,0 +1,357 @@
+/*
+ * 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.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.logging.LogEvent;
+import org.apache.maven.api.logging.LogLevel;
+import org.apache.maven.api.logging.LoggerManager;
+
+/**
+ * Immutable implementation of {@link LogEvent} with lazy message formatting.
+ * <p>
+ * When constructed with a {@code messageTemplate} and {@code messageArgs},
+ * the formatted {@link #message()} is computed lazily on first access.
+ * When constructed with a pre-formatted message, it is returned as-is.
+ *
+ * @since 4.2.0
+ */
+public final class DefaultLogEvent implements LogEvent {
+
+    private final Instant timestamp;
+    private final LogLevel level;
+    private final String message;
+    private final String loggerName;
+    private final Throwable throwable;
+    private final String sourceClassName;
+    private final String sourceMethodName;
+    private final long threadId;
+    private final long sequenceNumber;
+    private final String threadName;
+    private final String projectId;
+    private final String mojoId;
+    private final String pluginId;
+    private final Map<String, Object> keyValues;
+    private final String messageTemplate;
+    private final List<Object> messageArgs;
+    private volatile String renderedLine;

Review Comment:
   🔍 **Class doc says "Immutable implementation" — now inaccurate**
   
   `renderedLine` changed from `private final` to `private volatile` and is 
mutated post-construction via lazy init. The class is *effectively* immutable 
(write-once lazy fields), but calling it "Immutable" contradicts the field 
declaration a few lines below, and will confuse readers who check if the class 
is thread-safe.
   
   Update the class-level Javadoc to say "effectively immutable" and explicitly 
mention that `renderedLine()` (like `message()`) is lazily computed:
   
   ```suggestion
       private volatile String renderedLine;
   ```
   
   (The field declaration is correct. Update the class Javadoc at line 32 to: 
`"Effectively immutable implementation of {@link LogEvent} with lazy 
formatting. The {@link #message()} and {@link #renderedLine()} fields are 
computed lazily on first access; all other fields are set at construction time 
and never mutated."`)



##########
impl/maven-logging/src/main/java/org/apache/maven/logging/impl/DefaultLoggerManager.java:
##########
@@ -0,0 +1,460 @@
+/*
+ * 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<>());
+
+    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) {
+        StringBuilder buf = new StringBuilder(80);
+
+        // Timestamp
+        if (getBooleanProperty(Constants.MAVEN_LOGGER_SHOW_DATE_TIME, false)) {
+            String format = 
getStringProperty(Constants.MAVEN_LOGGER_DATE_TIME_FORMAT, null);
+            Instant ts = event.timestamp();
+            if (ts != null) {
+                if (format != null && !format.isEmpty()) {
+                    buf.append(DateTimeFormatter.ofPattern(format)
+                            .withZone(ZoneId.systemDefault())
+                            .format(ts));

Review Comment:
   🟡 **`DateTimeFormatter` allocated per log event on the hot rendering path**
   
   `DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault())` 
creates a new `DateTimeFormatter` on every `formatLine()` call. 
`DateTimeFormatter` is immutable and thread-safe — it should be cached. When 
`MAVEN_LOGGER_SHOW_DATE_TIME=true` is set (e.g. in CI), every log event 
allocates one, which adds GC pressure on a build that may emit tens of 
thousands of log lines.
   
   The format string comes from a system property read at startup — it doesn't 
change mid-build. Cache it alongside a parsed `DateTimeFormatter`:
   
   ```suggestion
                   if (format != null && !format.isEmpty()) {
                       DateTimeFormatter dtf = 
DateTimeFormatter.ofPattern(format)
                               .withZone(ZoneId.systemDefault());
                       buf.append(dtf.format(ts));
   ```
   
   (Proper fix: add `private volatile DateTimeFormatter 
cachedDateTimeFormatter` and `private volatile String cachedDateTimeFormat` 
instance fields, check if format matches cached one, and rebuild only on 
change.)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to