gnodet-bot commented on code in PR #13832: URL: https://github.com/apache/maven/pull/13832#discussion_r4621877590
########## api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogEvent.java: ########## @@ -0,0 +1,257 @@ +/* + * 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.api.logging; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import org.apache.maven.api.annotations.Experimental; +import org.apache.maven.api.annotations.Immutable; +import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.annotations.Nullable; +import org.apache.maven.api.annotations.Provider; + +/** + * A structured log event captured during the build. + * <p> + * Each event carries the log level, timestamp, message, and optionally + * the logger name and a stack trace. This replaces raw log line strings + * in the build report, enabling programmatic filtering by level and + * correlation by timestamp. + * <p> + * Events originating from the Maven Log API or from JUL + * ({@code java.util.logging}) carry additional source metadata: the + * source class name, source method name, and thread identifier. + * For Log API events the source class name is the mojo implementation + * FQCN; for JUL events it comes from {@code LogRecord}. Events from + * direct SLF4J logging have these fields set to {@code null}. + * <p> + * Events produced via the fluent {@link LogEventBuilder} API may additionally + * carry structured key-value pairs ({@link #keyValues()}) and the raw + * unformatted message template ({@link #messageTemplate()}, + * {@link #messageArgs()}) alongside the formatted {@link #message()}. + * + * @since 4.2.0 + */ +@Experimental +@Immutable +@Provider +public interface LogEvent { + + /** + * When this log event was produced (wall-clock time). + * + * @return the event instant, never {@code null} + */ + @Nonnull + Instant timestamp(); + + /** + * The severity level of this log event. + * + * @return the log level, never {@code null} + */ + @Nonnull + LogLevel level(); + + /** + * The log message, without level prefix or timestamp formatting. + * <p> + * When the event was produced via {@link LogEventBuilder#log(String, Object...)} + * this is the formatted result. When no template args were supplied it is + * the literal message string. + * + * @return the log message, never {@code null} + */ + @Nonnull + String message(); + + /** + * The name of the logger that produced this event + * (e.g. {@code "org.apache.maven.plugins.compiler.CompilerMojo"}). + * + * @return the logger name, or {@code null} if unavailable + */ + @Nullable + String loggerName(); + + /** + * The original exception that triggered this log event, if available. + * + * @return the original throwable, or {@code null} + */ + @Nullable + default Throwable throwable() { + return null; + } + + // ---- Source metadata (populated for Log API and JUL events) ---- + + /** + * The fully qualified class name of the source that issued the log call. + * <p> + * For Maven Log API events this is the mojo implementation class name. + * For JUL events it is the value from {@code LogRecord.getSourceClassName()}. + * For direct SLF4J logging it is {@code null}. + * + * @return the source class name, or {@code null} + */ + @Nullable + default String sourceClassName() { + return null; + } + + /** + * The method name of the source that issued the log call. + * <p> + * For Maven Log API events this is resolved via {@link StackWalker}. + * For JUL events it is the value from {@code LogRecord.getSourceMethodName()}. + * For direct SLF4J logging it is {@code null}. + * + * @return the source method name, or {@code null} + */ + @Nullable + default String sourceMethodName() { + return null; + } + + /** + * The thread identifier from which this log event originated. + * + * @return the thread ID, or {@code -1} if unavailable + */ + default long threadId() { + return -1; + } + + /** + * The name of the thread from which this log event originated. + * + * @return the thread name, or {@code null} if unavailable + */ + @Nullable + default String threadName() { + return null; + } + + /** + * A monotonically increasing sequence number for total ordering of log events. + * + * @return the sequence number, or {@code -1} if unavailable + */ + default long sequenceNumber() { + return -1; + } + + /** + * The project this log event belongs to + * (e.g. {@code "org.apache.maven:maven-core:4.1.0-SNAPSHOT"}), or {@code null} + * if the event was not produced in the context of a specific project. + * + * @return the project identifier, or {@code null} + */ + @Nullable + default String projectId() { + return null; + } + + /** + * The mojo execution that produced this event + * (e.g. {@code "compiler:compile@default-compile"}), or {@code null} + * if the event was logged outside a mojo execution. + * + * @return the mojo execution identifier, or {@code null} + */ + @Nullable + default String mojoId() { + return null; + } + + /** + * The plugin that produced this event + * (e.g. {@code "org.apache.maven.plugins:maven-compiler-plugin:3.13.0"}), or {@code null} + * if the event was logged by Maven core or outside a plugin context. + * + * @return the plugin identifier, or {@code null} + * @since 4.2.0 + */ + @Nullable + default String pluginId() { + return null; + } + + // ---- Structured data (populated for fluent LogBuilder events) ---- + + /** + * Structured key-value pairs attached to this event via + * {@link LogEventBuilder#withKeyValue(String, String)} and its overloads. + * <p> + * Returns an empty map when no key-value pairs were supplied. + * + * @return an immutable map of key-value pairs (values may be {@code String}, + * {@code Long}, or {@code Boolean}), never {@code null} + */ + @Nonnull + default Map<String, Object> keyValues() { + return Map.of(); + } + + /** + * The pre-rendered console line produced by the SLF4J logger, including level prefix + * and ANSI color codes, or {@code null} when the event was not produced via SLF4J. Review Comment: 🔍 **`renderedLine()` Javadoc no longer accurate after lazy-formatting change** `DefaultLogEvent.renderedLine()` (introduced in commit `cbe9cdb6`) now **never** returns `null` — it lazily delegates to `LoggerManager.get().formatLine(this)` for all events, including non-SLF4J ones. The description "or `null` when the event was not produced via SLF4J" is now misleading for `DefaultLogEvent` consumers. The `@Nullable` annotation on the interface default method is technically correct (custom implementations may still return `null`), but the Javadoc text needs updating to explain both cases: ```suggestion * The pre-rendered console line including level prefix and ANSI color codes. * <p> * The default implementation returns {@code null}; {@code DefaultLogEvent} * lazily delegates to {@link LoggerManager#formatLine(LogEvent)} and always * produces a non-null result. Custom implementations may still return * {@code null} — console sinks should fall back to {@link #message()} in that case. ``` ########## impl/maven-logging-slf4j/src/main/java/org/apache/maven/logging/slf4j/MavenSimpleLogger.java: ########## @@ -0,0 +1,176 @@ +/* + * 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.slf4j; + +import java.util.Arrays; +import java.util.Map; + +import org.apache.maven.api.MonotonicClock; +import org.apache.maven.api.logging.LogLevel; +import org.apache.maven.api.logging.LogSink; +import org.apache.maven.api.logging.LoggerManager; +import org.apache.maven.logging.impl.DefaultLogEvent; +import org.apache.maven.logging.impl.DefaultLoggerManager; +import org.slf4j.Marker; +import org.slf4j.event.Level; +import org.slf4j.helpers.LegacyAbstractLogger; +import org.slf4j.spi.LocationAwareLogger; + +/** + * Thin SLF4J logger that dispatches events to the Maven unified logging API + * via {@link LoggerManager}. Level checks are delegated to + * {@link DefaultLoggerManager}; formatting is deferred to the {@link LogSink}. + * + * @since 4.2.0 + */ +public class MavenSimpleLogger extends LegacyAbstractLogger { + + private static final StackWalker STACK_WALKER = StackWalker.getInstance(); + final String pluginId; + volatile int currentLogLevel = LocationAwareLogger.INFO_INT; + + MavenSimpleLogger(String name) { + this(name, null); + } + + MavenSimpleLogger(String name, String pluginId) { + this.name = name; + this.pluginId = pluginId; + LoggerManager mgr = LoggerManager.get(); + if (mgr instanceof DefaultLoggerManager dlm) { + this.currentLogLevel = dlm.getLoggerLevel(name); + } + } + + @Override + protected void handleNormalizedLoggingCall( + Level level, Marker marker, String messagePattern, Object[] arguments, Throwable throwable) { + int intLevel = level.toInt(); + if (!isLevelEnabled(intLevel)) { + return; + } + + String mavenTemplate = Slf4jTemplateConverter.convert(messagePattern); + Object[] cleanArgs = throwable != null + && arguments != null + && arguments.length > 0 + && arguments[arguments.length - 1] == throwable + ? Arrays.copyOf(arguments, arguments.length - 1) + : arguments; + + LoggerManager mgr = LoggerManager.get(); + LogSink sink = mgr.getLogSink(); + if (sink != null) { + LogLevel logLevel = toLogLevel(intLevel); + DefaultLoggerManager dlm = mgr instanceof DefaultLoggerManager d ? d : null; + + String sourceClass = null; + String sourceMethod = null; + if (sink.needsMetadata()) { + StackWalker.StackFrame caller = STACK_WALKER.walk( + frames -> frames.dropWhile(f -> f.getClassName().startsWith("org.slf4j.") + || f.getClassName().startsWith("org.apache.maven.logging.slf4j.")) + .findFirst() + .orElse(null)); + if (caller != null) { + sourceClass = caller.getClassName(); + sourceMethod = caller.getMethodName(); + } + } + + sink.accept(new DefaultLogEvent( + MonotonicClock.now(), + logLevel, + null, + name, + throwable, + sourceClass, + sourceMethod, + Thread.currentThread().getId(), Review Comment: 🔍 **`Thread.currentThread().getId()` is deprecated since JDK 19** This new class uses `Thread.currentThread().getId()` without a TODO comment, while `DefaultLogger.java` (line ~1680 in the diff) already has `// TODO: replace with threadId() when baseline ≥ JDK 19`. For consistency, either add the same TODO or switch to `Thread.currentThread().threadId()` now if the build baseline permits. ```suggestion Thread.currentThread().threadId(), ``` ########## impl/maven-logging/src/test/java/org/apache/maven/logging/impl/DefaultLoggerManagerTest.java: ########## @@ -0,0 +1,65 @@ +/* + * 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 org.apache.maven.api.logging.LogLevel; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class DefaultLoggerManagerTest { + + @Test + void hasReachedTracksMaxLevel() { + DefaultLoggerManager manager = new DefaultLoggerManager(); + + assertFalse(manager.hasReached(LogLevel.WARN)); + + manager.record(LogLevel.INFO); + assertFalse(manager.hasReached(LogLevel.WARN)); + + manager.record(LogLevel.WARN); + assertTrue(manager.hasReached(LogLevel.WARN)); + + manager.record(LogLevel.INFO); + assertTrue(manager.hasReached(LogLevel.WARN), "max should not decrease"); + } + + @Test + void reconfigureResetsMaxLevel() { + DefaultLoggerManager manager = new DefaultLoggerManager(); + manager.record(LogLevel.ERROR); + assertTrue(manager.hasReached(LogLevel.WARN)); + + manager.reconfigure(); + assertFalse(manager.hasReached(LogLevel.WARN)); + } + + @Test + void isLevelEnabledDefaultsToInfo() { + DefaultLoggerManager manager = new DefaultLoggerManager(); + + assertTrue(manager.isLevelEnabled("test", LogLevel.INFO)); + assertTrue(manager.isLevelEnabled("test", LogLevel.WARN)); + assertTrue(manager.isLevelEnabled("test", LogLevel.ERROR)); + assertFalse(manager.isLevelEnabled("test", LogLevel.DEBUG)); + assertFalse(manager.isLevelEnabled("test", LogLevel.TRACE)); + } +} Review Comment: 🔍 **Missing test for the lazy `renderedLine()` → `formatLine()` path** `DefaultLoggerManagerTest` tests `hasReached`, `reconfigure`, and `isLevelEnabled` but does not cover `formatLine()`. The lazy delegation path in `DefaultLogEvent.renderedLine()` (commit `cbe9cdb6`) is the core rendering mechanism and is exercised only by the JMH benchmark — not a correctness test. A minimal test that pins the behaviour: ```java @Test void formatLineProducesNonNullRenderedLine() { DefaultLoggerManager manager = new DefaultLoggerManager(); LoggerManager.set(manager); try { DefaultLogEvent event = new DefaultLogEvent( null, LogLevel.INFO, "hello world", "test.Logger", null); String line = event.renderedLine(); assertNotNull(line); assertTrue(line.contains("hello world"), "formatted line must contain the message"); assertTrue(line.contains("INFO") || line.contains("\u001b"), "formatted line must contain level"); } finally { LoggerManager.set(null); } } ``` -- 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]
