You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@maven.apache.org by "gnodet (via GitHub)" <gi...@apache.org> on 2026/08/07 17:14:03 UTC
[PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
gnodet opened a new pull request, #12694:
URL: https://github.com/apache/maven/pull/12694
## Summary
Focused, reviewable PR that lays the logging infrastructure foundation for the build report work (#12572). Split out from #12572 to enable focused review and discussion of the logging architecture.
### What's included
**Log API enhancements** (`maven-api-core`)
- `Log.trace()` — 5 overloads + `isTraceEnabled()` to separate Maven core internals (trace) from user-facing debug output (debug). Maps to SLF4J TRACE / JUL FINEST.
- `Log.child(name)` — hierarchical sub-loggers for plugins that want to separate concerns while keeping level control. Default implementation returns `this` for backward compatibility.
**Structured LogEvent** (`maven-api-core`, `maven-core`)
- `LogEvent` / `LogLevel` API for structured log event representation
- Optional JUL metadata fields: `sourceClassName()`, `sourceMethodName()`, `threadId()` — populated only for events originating from `java.util.logging`, `null` for SLF4J/Log API events
**Custom JUL Handler** (`maven-logging`)
- `MavenJulHandler` replaces `SLF4JBridgeHandler` — reimplements JUL→SLF4J bridging while preserving the full `LogRecord` metadata that the standard bridge silently drops
- Uses a ThreadLocal to pass JUL metadata synchronously to `ProjectBuildLogAppender` during the same `publish()` call
- Three code paths, one pipeline: Log API → SLF4J, SLF4J direct, JUL → `MavenJulHandler` → SLF4J — all converge on the same structured `LogEvent`
**Structured LogSink** (`maven-logging`, `maven-core`)
- `MavenSimpleLogger.LogSink` — structured callback with `(level, loggerName, cleanMessage, formattedMessage, throwable)` replacing the old `Consumer<String>` sink
- `ProjectBuildLogAppender` produces `LogEvent` objects (with JUL metadata when available) instead of raw strings
- `BuildEventListener.projectLogMessage()` now takes `LogEvent` instead of `String`
**Mojo MDC & logger name** (`maven-core`)
- `maven.mojo.id` MDC key set during mojo execution (format: `prefix:goal@executionId`)
- Logger name changed from `getFullGoalName()` ("compiler:compile") to `getImplementation()` (FQCN like `org.apache.maven.plugins.compiler.CompilerMojo`) for proper hierarchical SLF4J level configuration
**Bug fix**
- `DefaultLog.warn(Supplier<String>, Throwable)` was calling `logger.info()` instead of `logger.warn()`
### Context
This is Part 1 of the #12572 split. The build report, console modes, and warning mode features will follow as separate PRs on top of this foundation. See discussion in the [dev@ thread](https://lists.apache.org/thread/...) and Martin's feedback on JUL field preservation.
### Depends on / blocks
- Blocks: #12572 (remaining build report features)
- Related: #12690 (4.0.x backport of Log API changes)
- Related: apache/maven-compiler-plugin#1101 (compiler plugin using Log API)
## Test plan
- [x] `mvn test -pl impl/maven-core,impl/maven-logging` — 580 tests pass
- [ ] Full CI validation
- [ ] IT suite with JUL-using plugins (verify metadata preservation)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3879506992
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,167 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
+ */
+ @Nullable
+ default String sourceMethodName() {
+ return null;
+ }
+
+ /**
+ * The thread identifier from which this log event originated.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ * @since 4.1.0
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @return the sequence number, always non-negative
+ * @since 4.1.0
+ */
+ default long sequenceNumber() {
+ return -1;
+ }
+}
Review Comment:
Fixed — javadoc now reads `@return the sequence number, or {@code -1} if unavailable`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,167 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
+ */
+ @Nullable
+ default String sourceMethodName() {
+ return null;
+ }
+
+ /**
+ * The thread identifier from which this log event originated.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ * @since 4.1.0
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @return the sequence number, always non-negative
+ * @since 4.1.0
+ */
+ default long sequenceNumber() {
+ return -1;
+ }
+}
Review Comment:
Fixed — javadoc now reads `@return the sequence number, or {@code -1} if unavailable`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057956410
##########
impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java:
##########
@@ -898,13 +899,12 @@ public Set<Artifact> getArtifacts() {
if (artifactFilter == null || resolvedArtifacts == null) {
artifacts = new LinkedHashSet<>();
} else {
- Set<Artifact> result = new LinkedHashSet<>(resolvedArtifacts.size() * 2);
+ artifacts = new LinkedHashSet<>(resolvedArtifacts.size() * 2);
for (Artifact artifact : resolvedArtifacts) {
if (artifactFilter.include(artifact)) {
- result.add(artifact);
+ artifacts.add(artifact);
}
Review Comment:
⚠️ **Concurrency regression — partially-populated `artifacts` visible to concurrent readers.**
The old code built into a local `result` variable and then assigned `artifacts = result` atomically as the last step. This squash eliminates the local variable and writes directly into `artifacts` during the loop — so concurrent callers of `getArtifacts()` can observe `artifacts != null` (because it was assigned on line 903) but iterate a set that is only half-populated (because the loop hasn't finished yet).
The deleted `MavenProjectGetArtifactsTest.concurrentGetArtifactsDoesNotExposeAHalfBuiltSet()` existed precisely to catch this race. Restoring the intermediate variable also restores the test.
```suggestion
Set<Artifact> result = new LinkedHashSet<>(resolvedArtifacts.size() * 2);
for (Artifact artifact : resolvedArtifacts) {
if (artifactFilter.include(artifact)) {
result.add(artifact);
}
}
artifacts = result;
```
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategy.java:
##########
@@ -560,28 +568,12 @@ private boolean upgradePropertyVersion(
return false; // Found in current POM, no upgrade needed
}
Review Comment:
⚠️ **Sibling-POM mutation regression — ancestor-directory guard removed.**
The deleted code (lines `-1093`..`-1112`) restricted the cross-POM property search to POMs in ancestor directories:
```java
if (candidateDir == null || !currentDir.startsWith(candidateDir)) {
continue;
}
```
This was intentional: in a multi-module project, if child-A and child-B both define property `maven.compiler.release` with sibling pom-A defining an old version, the old code correctly skipped sibling-A when upgrading from child-B. The new code iterates *all* POMs without that guard.
Concrete failure case: a project with `parent/pom.xml` defining `${myPlugin.version}=3.0` and sibling `lib/pom.xml` defining `${myPlugin.version}=3.9`. When processing `app/pom.xml` (a child of `parent`), the code will now iterate both `lib/pom.xml` and `parent/pom.xml`, potentially upgrading the property in `lib/pom.xml` — a sibling of `app`, not its parent. That is incorrect.
The ancestor-directory filter must be restored.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategy.java:
##########
@@ -289,8 +294,11 @@ public UpgradeResult doApply(UpgradeContext context, Map<Path, Document> pomMap)
}
}
+ // Clean up temp directory
+ cleanupTempDirectory(tempDir);
Review Comment:
⚠️ **Temp-directory leak when an exception is thrown.**
`cleanupTempDirectory(tempDir)` is inside the `try` block. If `analyzePluginsUsingEffectiveModels()` or any code between line 230 and 298 throws an uncaught exception, execution jumps to the outer `catch (Exception e)` block (line 300) and cleanup is never called. The temp directory in `/tmp` is leaked for the remainder of the JVM lifetime.
Fix: use `try/finally`, or capture the path before the try and clean up in the catch:
```suggestion
} finally {
cleanupTempDirectory(tempDir);
}
```
(Move the `cleanupTempDirectory` call into a `finally` block wrapping the inner logic, not the outer catch.)
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357363066
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
Review Comment:
> LogEvent is designed to be @Immutable and serialisable
drop last one, this is a consumer impl detail - keep immutable and early evaluation (ensure to call getThrowable and getSource* early so it is async friendly (impacts more the integration than the API but it is important to materialize since it is often lazy)
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357411702
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
Good question. exists because Maven is the SLF4J **provider** (not a consumer): it implements and supplies its own . That gives us control over every log call made by plugins and Maven itself — we can intercept at the source, before any formatting happens, and route to directly.
If we used an off-the-shelf SLF4J backend (Logback, Log4j2, the simple logger shipped with SLF4J) we'd have to either (a) configure it externally and lose the ability to swap the sink at runtime, or (b) write our own backend anyway — which is exactly what / are.
Long term the goal is for to do less: once the plugin / extension SPI converges on (maven-api-core), internal Maven code will use it directly, and can shrink to a thin SLF4J bridge. But that migration is a separate concern and happens incrementally across the PR chain — worth opening a follow-up issue if you'd like to track it.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046932914
##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java:
##########
@@ -18,21 +18,81 @@
*/
package org.apache.maven.internal.impl;
+import java.lang.StackWalker.StackFrame;
import java.util.function.Supplier;
import org.apache.maven.api.plugin.Log;
+import org.apache.maven.logging.ProjectBuildLogAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
public class DefaultLog implements Log {
+
+ /**
+ * Metadata captured from Log API calls, mirroring the JUL metadata
+ * pattern in {@code MavenJulHandler}.
+ *
+ * @param sourceClassName the fully qualified class name of the caller
+ * @param sourceMethodName the method that issued the log call
+ * @param threadId the originating thread ID
+ */
+ public record LogApiMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<LogApiMetadata> LOG_API_METADATA = new ThreadLocal<>();
+ private static final StackWalker WALKER = StackWalker.getInstance();
+ private static final String THIS_CLASS = DefaultLog.class.getName();
+
+ /**
+ * Returns the Log API metadata for the current log event being processed,
+ * or {@code null} if the current event did not originate from the Log API.
+ * <p>
+ * Called from {@code ProjectBuildLogAppender.accept()} to populate
+ * {@code LogEvent.sourceClassName()} and {@code LogEvent.sourceMethodName()}.
+ *
+ * @return the current Log API metadata, or {@code null}
+ */
+ public static LogApiMetadata getLogApiMetadata() {
+ return LOG_API_METADATA.get();
+ }
+
private final Logger logger;
public DefaultLog(Logger logger) {
this.logger = requireNonNull(logger);
}
+ /**
+ * Wraps a logging call with Log API metadata: sets the ThreadLocal with
+ * source class name and thread ID, executes the actual SLF4J call, and
+ * clears the ThreadLocal.
+ * <p>
+ * The source class name is taken from the SLF4J logger name (which
+ * is the mojo implementation FQCN, set at injection time). The
+ * source method name is resolved via {@link StackWalker} only when
+ * build report capture is active (to avoid the ~1-5μs per-call cost
+ * on every enabled log statement during normal builds).
+ */
+ private void withMetadata(Runnable logAction) {
+ // Only pay the StackWalker cost when someone is actually capturing metadata
+ String callerMethodName = null;
+ if (ProjectBuildLogAppender.hasReportCapture()) {
+ callerMethodName = WALKER.walk(frames -> frames.dropWhile(f -> THIS_CLASS.equals(f.getClassName()))
+ .findFirst()
+ .map(StackFrame::getMethodName)
+ .orElse(null));
+ }
+ @SuppressWarnings("deprecation") // Thread.getId() — threadId() requires Java 19+
+ long threadId = Thread.currentThread().getId();
+ LOG_API_METADATA.set(new LogApiMetadata(logger.getName(), callerMethodName, threadId));
Review Comment:
Fixed in ad8a390432674ef54e547174fa7a5c034b86aba7. Moved the entire `withMetadata` body — ThreadLocal.set(), LogApiMetadata record allocation, StackWalker walk, and ThreadLocal.remove() — inside the `hasReportCapture()` branch. Normal builds now call `logAction.run()` directly with zero ThreadLocal cost; the allocation and set/remove only run when build report capture is active.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4052287691
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
**[low] `logApiMetadataIsClearedAfterCall()` is trivially true — never exercises the `remove()` path**
The test calls `log.info("test message")` with a plain mock logger and no `ProjectBuildLogAppender` installed. `withMetadata()` checks `ProjectBuildLogAppender.hasReportCapture()`, which returns `false` in this test context. It therefore takes the `else` branch — just `logAction.run()` — and never sets `LOG_API_METADATA` at all. The final `assertNull(DefaultLog.getLogApiMetadata())` passes because the ThreadLocal was never written, not because `remove()` cleaned it up.
To actually exercise the contract, the test needs to enable report capture (install a stub `BuildEventListener` and call `ProjectBuildLogAppender`'s static setter) and then verify that after the call the ThreadLocal is cleared — including in the face of a `logAction` that throws.
Fix: either mock `ProjectBuildLogAppender.hasReportCapture()` to return `true` (requires extracting the predicate or using a test hook) or instantiate a real `ProjectBuildLogAppender` with a capturing listener before the call and tear it down after.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
**[low] `@return` says "the formatted message" — copy-paste from `formattedMessage()`**
The body Javadoc on the preceding lines correctly says "The log message, without level prefix or timestamp formatting." But the `@return` tag contradicts it by saying "the formatted message" — the exact wording used by `formattedMessage()` two methods below. A reader will reasonably conclude that `message()` returns the same full formatted line as `formattedMessage()`, which is wrong.
```suggestion
* @return the clean log message (without level prefix or ANSI), never {@code 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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #12694:
URL: https://github.com/apache/maven/pull/12694#issuecomment-6360137849
Thanks for the review, Romain. Your inline comments have been addressed in the thread replies, but let me respond to the overall direction concern here.
The `LogEvent` API currently mixes two things:
1. **Log data** — `level()`, `message()`, `loggerName()`, `threadId()`, `instant()`, `stackTrace()` — these are intrinsic to the event.
2. **Rendering artefact** — `formattedMessage()` — this is a pre-rendered console line, which you rightly point out doesn't belong in a data structure.
I agree with you on `formattedMessage()`: it leaks a rendering concern into what should be a rendering-agnostic interface. I'm removing it. The consumer (`SimpleBuildEventListener` and the chain in PR #13180) will carry its own formatter — either a `LogEventFormatter` utility class or a `Function<LogEvent, String>` injected at construction. I'll coordinate with #13180 before finalising that.
On the other comments:
- **`message()` vs template+args**: JUL eagerly substitutes so no template is available; exposing it would create an inconsistent API. Keeping `message()` as the substituted string, `formattedMessage()` is gone.
- **`Throwable` vs `String`**: `@Immutable` + serialisation concern argues for `String`. I'm adding a default-null `throwable()` as an opt-in for consumers that need type-based filtering, alongside `stackTrace()` which stays for the general case.
- **Custom `LogManager`**: Adding the guard in `LookupInvoker` — check `LogManager.getLogManager().getClass() == LogManager.class` before touching root handlers.
- **Thread name**: Adding `threadName()` populated at capture time.
I'll address these in the next commit. The overall shape of the API (`LogEvent` as a data record of what was logged, not how it was rendered) is the goal — thanks for pushing on that.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357501436
##########
impl/maven-core/src/main/java/org/apache/maven/logging/SimpleBuildEventListener.java:
##########
@@ -38,8 +39,8 @@ public void sessionStarted(ExecutionEvent event) {}
public void projectStarted(String projectId) {}
@Override
- public void projectLogMessage(String projectId, String event) {
- log(event);
+ public void projectLogMessage(String projectId, LogEvent event) {
+ log(event.message());
Review Comment:
**[critical] Raw `event.message()` drops all log-level formatting.**
Before this commit, `MavenSimpleLogger` produced a fully formatted console line (e.g. `[INFO] Building my-project 1.0.0`) and that string was passed as `formattedMessage` to `SimpleBuildEventListener`. Now `formattedMessage()` is removed from the API and `needsFormattedMessage()` is hardcoded to `false`, so only the raw substituted text is available here. All standard Maven terminal output will lose its `[INFO]`/`[WARN]`/`[ERROR]` prefix, thread name, and timestamp.
Fix options:
1. Reconstruct from structured fields: `log("[" + event.level().name() + "] " + event.message())`
2. Inject a `LogEventFormatter` (the renderer concern stays outside the event, which is the right direction)
3. Make `MavenSimpleLogger.write()` call `super.write(buf, t)` unconditionally for console output and route the structured event separately to the sink
Option 2 is the cleanest long-term design — pass-through renderers should carry their own formatter, not rely on a pre-formatted field in the data structure.
```suggestion
public void projectLogMessage(String projectId, LogEvent event) {
log("[" + event.level().name() + "] " + event.message());
}
```
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -314,6 +331,23 @@ protected void configureLogging(C context) throws Exception {
} else if (context.options().quiet().orElse(false)) {
context.loggerLevel = Slf4jConfiguration.Level.ERROR;
context.slf4jConfiguration.setRootLoggerLevel(context.loggerLevel);
+ // Install the JUL handler early and clamp the JUL root to SEVERE
+ // so that JLine terminal-init DEBUG events (emitted via java.util.logging
+ // before activateLogging() runs) are suppressed at source.
+ // createTerminal() executes after configureLogging() but before
+ // activateLogging(), so without this guard those DEBUG lines leak
+ // into the build output even when -q is in effect, causing
+ // MavenITmng4387QuietLoggingTest to fail on Windows.
+ // Setting SEVERE here is safe: it only blocks events, so it
+ // cannot trigger the SLF4J-bootstrap reentrancy flood that
+ // Level.ALL would cause.
+ if (LogManager.getLogManager().getClass() == LogManager.class
+ && !MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
+ }
+ if (LogManager.getLogManager().getClass() == LogManager.class) {
+ LogManager.getLogManager().getLogger("").setLevel(Level.SEVERE);
Review Comment:
**[low] `LogManager.getLogManager()` called redundantly** — 3 times in this method alone (lines 344, 348, 349), and 7 times total across `invoke()`, `configureLogging()`, and `activateLogging()`.
The `LogManager` singleton doesn't change at runtime; cache it in a local variable at the top of each method:
```java
LogManager logManager = LogManager.getLogManager();
if (logManager.getClass() == LogManager.class && !MavenJulHandler.isInstalled()) {
MavenJulHandler.install();
}
if (logManager.getClass() == LogManager.class) {
logManager.getLogger("").setLevel(Level.SEVERE);
}
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3743158594
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,167 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
+ */
+ @Nullable
+ default String sourceMethodName() {
+ return null;
+ }
+
+ /**
+ * The thread identifier from which this log event originated.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ * @since 4.1.0
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @return the sequence number, always non-negative
+ * @since 4.1.0
+ */
+ default long sequenceNumber() {
+ return -1;
+ }
+}
Review Comment:
The `@return` Javadoc says "always non-negative" but the default implementation returns `-1`, and `DefaultLogEvent` convenience constructors also pass `-1`. The `threadId()` method in this same interface correctly documents its sentinel ("or -1 if unavailable").
```suggestion
* @return the sequence number, or {@code -1} if unavailable
```
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.apache.maven.api.services.MessageBuilder;
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.apache.maven.jline.MessageUtils.builder;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * When a {@link MavenSimpleLogger.LogSink LogSink} is installed (i.e. during
+ * a build), JUL events are sent directly to the sink — bypassing SLF4J
+ * entirely. The JUL metadata is stashed in a thread-local so downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * When no LogSink is installed (e.g. during early bootstrap), the handler
+ * falls back to routing through SLF4J for console output.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Returns the JUL metadata for the current log event being processed,
+ * or {@code null} if the current log event did not originate from JUL.
+ * <p>
+ * This method is intended to be called from within a
+ * {@link MavenSimpleLogger.LogSink} callback (e.g. in
+ * {@code ProjectBuildLogAppender.accept()}).
+ *
+ * @return the current JUL metadata, or {@code null}
+ */
+ public static JulMetadata getJulMetadata() {
+ return METADATA.get();
+ }
+
+ /**
+ * Installs this handler on the JUL root logger, removing any
+ * previously installed handlers. This replaces the standard
+ * {@code SLF4JBridgeHandler.install()} call.
+ */
+ public static void install() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ // Remove all existing handlers (including any SLF4JBridgeHandler)
+ for (Handler handler : rootLogger.getHandlers()) {
+ rootLogger.removeHandler(handler);
+ }
+ rootLogger.addHandler(new MavenJulHandler());
+ // Accept all levels — filtering is done by SLF4J
+ rootLogger.setLevel(Level.ALL);
+ }
+
+ /**
+ * Returns {@code true} if a {@code MavenJulHandler} is installed
+ * on the JUL root logger.
+ */
+ public static boolean isInstalled() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ for (Handler handler : rootLogger.getHandlers()) {
+ if (handler instanceof MavenJulHandler) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void publish(LogRecord record) {
+ if (record == null) {
+ return;
+ }
+
+ String loggerName = record.getLoggerName();
+ org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(loggerName);
+ int slf4jLevel = julLevelToSlf4j(record.getLevel());
+
+ // Quick exit if this level is not enabled
+ if (!isLevelEnabled(slf4jLogger, slf4jLevel)) {
+ return;
+ }
+
+ String message = formatMessage(record);
+ Throwable throwable = record.getThrown();
+
+ // If a LogSink is installed, bypass SLF4J entirely: call the sink
+ // directly with the JUL metadata so no information is lost in transit.
+ MavenSimpleLogger.LogSink sink = MavenSimpleLogger.getLogSink();
+ if (sink != null) {
+ METADATA.set(new JulMetadata(
+ record.getSourceClassName(), record.getSourceMethodName(), record.getLongThreadID()));
+ try {
+ String formatted = formatForConsole(slf4jLevel, message);
+ sink.accept(slf4jLevel, loggerName, message, formatted, throwable);
+ } finally {
+ METADATA.remove();
+ }
+ } else {
+ // No LogSink — fall through to SLF4J for console output
+ logToSlf4j(slf4jLogger, slf4jLevel, message, throwable);
+ }
+ }
+
+ @Override
+ public void flush() {
+ // nothing to flush
+ }
+
+ @Override
+ public void close() throws SecurityException {
+ // nothing to close
+ }
+
+ /**
+ * Formats the log message, applying i18n resource bundle lookup and
+ * {@link MessageFormat} parameter substitution, matching the behavior
+ * of {@code SLF4JBridgeHandler}.
+ */
Review Comment:
`formatForConsole()` produces `[LEVEL] message` (no timestamp, no logger name), while `MavenSimpleLogger` produces a full formatted line with timestamp and logger name per configuration. This means `LogEvent.formattedMessage()` has an inconsistent format depending on whether the event originated from JUL or SLF4J. The `formattedMessage()` Javadoc promises "the level prefix, timestamp, and any ANSI styling" — JUL-sourced events would be missing the timestamp and logger name.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357255444
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the log message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
Good question. The design here separates two different use cases:
- `message()` — the raw text, no format specifiers, no template placeholders. This is what SLF4J gives us after argument substitution (via `MessageFormatter.arrayFormat()`). Both JUL events (after `MessageFormat.format()`) and SLF4J events produce a fully substituted string.
- `formattedMessage()` — the fully rendered console line: `[INFO] message\n` with optional ANSI, timestamp prefix, etc.
We don't have the original template + args because SLF4J's `LoggingEvent` does carry them (`getMessage()`/`getArgumentArray()`), but JUL's `LogRecord` substitutes eagerly. Exposing a template+args API would mean SLF4J events could provide it but JUL events could not, creating an inconsistent interface.
If you feel strongly about a template+args API: we could add `messageTemplate()` and `messageArgs()` default-null methods for the SLF4J path and document that they're unavailable for JUL events. But my concern is that consumers would have to implement two code paths — check if template+args are available, fall back to `message()` otherwise — adding complexity with little gain over just using `message()` everywhere.
As for why we have both `message()` and `formattedMessage()`: `message()` is for programmatic consumers (build report filters, structured log exporters). `formattedMessage()` is for pass-through renderers that want to emit exactly what the terminal would have shown. They serve different audiences. I can drop `formattedMessage()` from the API interface (see Romain's other comment on that) and expose it only at the impl level if you agree.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046864819
##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java:
##########
@@ -18,21 +18,81 @@
*/
package org.apache.maven.internal.impl;
+import java.lang.StackWalker.StackFrame;
import java.util.function.Supplier;
import org.apache.maven.api.plugin.Log;
+import org.apache.maven.logging.ProjectBuildLogAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
public class DefaultLog implements Log {
+
+ /**
+ * Metadata captured from Log API calls, mirroring the JUL metadata
+ * pattern in {@code MavenJulHandler}.
+ *
+ * @param sourceClassName the fully qualified class name of the caller
+ * @param sourceMethodName the method that issued the log call
+ * @param threadId the originating thread ID
+ */
+ public record LogApiMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<LogApiMetadata> LOG_API_METADATA = new ThreadLocal<>();
+ private static final StackWalker WALKER = StackWalker.getInstance();
+ private static final String THIS_CLASS = DefaultLog.class.getName();
+
+ /**
+ * Returns the Log API metadata for the current log event being processed,
+ * or {@code null} if the current event did not originate from the Log API.
+ * <p>
+ * Called from {@code ProjectBuildLogAppender.accept()} to populate
+ * {@code LogEvent.sourceClassName()} and {@code LogEvent.sourceMethodName()}.
+ *
+ * @return the current Log API metadata, or {@code null}
+ */
+ public static LogApiMetadata getLogApiMetadata() {
+ return LOG_API_METADATA.get();
+ }
+
private final Logger logger;
public DefaultLog(Logger logger) {
this.logger = requireNonNull(logger);
}
+ /**
+ * Wraps a logging call with Log API metadata: sets the ThreadLocal with
+ * source class name and thread ID, executes the actual SLF4J call, and
+ * clears the ThreadLocal.
+ * <p>
+ * The source class name is taken from the SLF4J logger name (which
+ * is the mojo implementation FQCN, set at injection time). The
+ * source method name is resolved via {@link StackWalker} only when
+ * build report capture is active (to avoid the ~1-5μs per-call cost
+ * on every enabled log statement during normal builds).
+ */
+ private void withMetadata(Runnable logAction) {
+ // Only pay the StackWalker cost when someone is actually capturing metadata
+ String callerMethodName = null;
+ if (ProjectBuildLogAppender.hasReportCapture()) {
+ callerMethodName = WALKER.walk(frames -> frames.dropWhile(f -> THIS_CLASS.equals(f.getClassName()))
+ .findFirst()
+ .map(StackFrame::getMethodName)
+ .orElse(null));
+ }
+ @SuppressWarnings("deprecation") // Thread.getId() — threadId() requires Java 19+
+ long threadId = Thread.currentThread().getId();
+ LOG_API_METADATA.set(new LogApiMetadata(logger.getName(), callerMethodName, threadId));
Review Comment:
**[medium] `LOG_API_METADATA.set()` + `remove()` run unconditionally — not zero-overhead in normal builds**
The StackWalker call is correctly gated behind `hasReportCapture()`, but `Thread.currentThread().getId()`, the `new LogApiMetadata(...)` allocation, `LOG_API_METADATA.set()`, and `LOG_API_METADATA.remove()` execute on every enabled mojo log call regardless. The PR description says "~1-5μs per-call cost only when build report capture is active" — that understates the real overhead. `ThreadLocal.set()` + GC pressure from a `LogApiMetadata` record allocation per call is non-zero at INFO level across a multi-module build.
Either move the entire `withMetadata` body inside the `hasReportCapture()` check and fall back to a direct call, or correct the documentation to reflect the actual cost:
```suggestion
private void withMetadata(Runnable logAction) {
if (ProjectBuildLogAppender.hasReportCapture()) {
// Only pay the StackWalker + ThreadLocal cost when metadata is needed
String callerMethodName = WALKER.walk(frames -> frames.dropWhile(f -> THIS_CLASS.equals(f.getClassName()))
.findFirst()
.map(StackFrame::getMethodName)
.orElse(null));
@SuppressWarnings("deprecation") // Thread.getId() — threadId() requires Java 19+
long threadId = Thread.currentThread().getId();
LOG_API_METADATA.set(new LogApiMetadata(logger.getName(), callerMethodName, threadId));
try {
logAction.run();
} finally {
LOG_API_METADATA.remove();
}
} else {
logAction.run();
}
}
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046898280
##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java:
##########
@@ -18,21 +18,81 @@
*/
package org.apache.maven.internal.impl;
+import java.lang.StackWalker.StackFrame;
import java.util.function.Supplier;
import org.apache.maven.api.plugin.Log;
+import org.apache.maven.logging.ProjectBuildLogAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
public class DefaultLog implements Log {
+
+ /**
+ * Metadata captured from Log API calls, mirroring the JUL metadata
+ * pattern in {@code MavenJulHandler}.
+ *
+ * @param sourceClassName the fully qualified class name of the caller
+ * @param sourceMethodName the method that issued the log call
+ * @param threadId the originating thread ID
+ */
+ public record LogApiMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<LogApiMetadata> LOG_API_METADATA = new ThreadLocal<>();
+ private static final StackWalker WALKER = StackWalker.getInstance();
+ private static final String THIS_CLASS = DefaultLog.class.getName();
+
+ /**
+ * Returns the Log API metadata for the current log event being processed,
+ * or {@code null} if the current event did not originate from the Log API.
+ * <p>
+ * Called from {@code ProjectBuildLogAppender.accept()} to populate
+ * {@code LogEvent.sourceClassName()} and {@code LogEvent.sourceMethodName()}.
+ *
+ * @return the current Log API metadata, or {@code null}
+ */
+ public static LogApiMetadata getLogApiMetadata() {
+ return LOG_API_METADATA.get();
+ }
+
private final Logger logger;
public DefaultLog(Logger logger) {
this.logger = requireNonNull(logger);
}
+ /**
+ * Wraps a logging call with Log API metadata: sets the ThreadLocal with
+ * source class name and thread ID, executes the actual SLF4J call, and
+ * clears the ThreadLocal.
+ * <p>
+ * The source class name is taken from the SLF4J logger name (which
+ * is the mojo implementation FQCN, set at injection time). The
+ * source method name is resolved via {@link StackWalker} only when
+ * build report capture is active (to avoid the ~1-5μs per-call cost
+ * on every enabled log statement during normal builds).
+ */
+ private void withMetadata(Runnable logAction) {
+ // Only pay the StackWalker cost when someone is actually capturing metadata
+ String callerMethodName = null;
+ if (ProjectBuildLogAppender.hasReportCapture()) {
+ callerMethodName = WALKER.walk(frames -> frames.dropWhile(f -> THIS_CLASS.equals(f.getClassName()))
+ .findFirst()
+ .map(StackFrame::getMethodName)
+ .orElse(null));
+ }
+ @SuppressWarnings("deprecation") // Thread.getId() — threadId() requires Java 19+
+ long threadId = Thread.currentThread().getId();
+ LOG_API_METADATA.set(new LogApiMetadata(logger.getName(), callerMethodName, threadId));
Review Comment:
Fixed in 3a363b335e. Moved the entire `withMetadata` body — ThreadLocal.set(), LogApiMetadata record allocation, and ThreadLocal.remove() — inside the `hasReportCapture()` branch. Normal builds now pay zero ThreadLocal cost; the allocation and set/remove only run when build report capture is active.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048592178
##########
impl/maven-core/src/main/resources/org/apache/maven/lifecycle/plugin-versions.properties:
##########
@@ -17,19 +17,19 @@
# Default lifecycle plugin versions.
# Values are substituted by Maven resource filtering at build time from
-# POM properties (lifecycle.<name>-plugin), making them visible to
+# POM properties (version.maven-<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
-lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
-lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
-lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
-lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
-lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
-lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
-lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
-lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
-lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
-lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
-lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
-lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
-lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
+version.maven-clean-plugin=${version.maven-clean-plugin}
Review Comment:
**[high] Property key rename not matched in `pom.xml` — CI breaks with `ExceptionInInitializerError`**
This file now uses `version.maven-*-plugin` keys, and `PluginVersions.java` looks up `"version." + pluginArtifactId`. But `impl/maven-core/pom.xml` (head commit `98cb72b4`) still declares the properties under the old `lifecycle.maven-*-plugin` names:
```xml
<lifecycle.maven-clean-plugin>3.5.0</lifecycle.maven-clean-plugin>
```
Maven's resource filtering substitutes `${version.maven-clean-plugin}` only if a property named `version.maven-clean-plugin` exists in the POM. Since it doesn't, the placeholder is left unresolved, and `PluginVersions.version()` hits the `version.startsWith("${")` guard and throws `ExceptionInInitializerError`. This is confirmed by the CI failure:
```
Tests run: 14, Failures: 0, Errors: 14 — in LifecycleExecutorTest
at org.apache.maven.lifecycle.PluginVersions.version(PluginVersions.java:60)
at org.apache.maven.lifecycle.PluginVersions.<clinit>(PluginVersions.java:71)
```
Fix: rename the 13 `<lifecycle.maven-*-plugin>` properties in `impl/maven-core/pom.xml` to `<version.maven-*-plugin>`, and update the `${lifecycle.maven-*-plugin}` expressions in the `<pluginManagement>` section to `${version.maven-*-plugin}`. The `versions-update` profile (now removed) also referenced these names, but that's deleted in this PR.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057965843
##########
impl/maven-core/src/main/java/org/apache/maven/project/MavenProject.java:
##########
@@ -898,13 +899,12 @@ public Set<Artifact> getArtifacts() {
if (artifactFilter == null || resolvedArtifacts == null) {
artifacts = new LinkedHashSet<>();
} else {
- Set<Artifact> result = new LinkedHashSet<>(resolvedArtifacts.size() * 2);
+ artifacts = new LinkedHashSet<>(resolvedArtifacts.size() * 2);
for (Artifact artifact : resolvedArtifacts) {
if (artifactFilter.include(artifact)) {
- result.add(artifact);
+ artifacts.add(artifact);
}
Review Comment:
Fixed in 2272eae465: restored the local `result` variable so `artifacts` is only assigned after the loop completes. Concurrent readers can no longer observe a partially-populated set.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategy.java:
##########
@@ -289,8 +294,11 @@ public UpgradeResult doApply(UpgradeContext context, Map<Path, Document> pomMap)
}
}
+ // Clean up temp directory
+ cleanupTempDirectory(tempDir);
Review Comment:
Fixed in 2272eae465: declared `tempDir` before the `try` block (initialized to `null`) and moved `cleanupTempDirectory()` into a `finally` block with a null guard. The temp directory is now always cleaned up, even when an exception is thrown.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategy.java:
##########
@@ -560,28 +568,12 @@ private boolean upgradePropertyVersion(
return false; // Found in current POM, no upgrade needed
}
Review Comment:
Fixed in 2272eae465: restored the ancestor-directory guard — `currentPomPath`/`currentDir` lookup and the `candidateDir.startsWith` check — so only POMs in ancestor directories (potential Maven parents) are searched when looking up a property cross-POM.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4058099580
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/AbstractUpgradeStrategy.java:
##########
@@ -424,55 +318,29 @@ protected Path findCommonRoot(Set<Path> pomPaths) {
return commonRoot;
}
- /**
- * Returns the effective model for the given POM path.
- *
- * <p>Consults {@link #effectiveModelCache} first (populated by the {@code BUILD_PROJECT}
- * reactor pass in {@link #prebuildReactorModels}). If the path is not in the cache
- * (e.g. an external parent that was not part of the reactor), falls back to a
- * {@code BUILD_EFFECTIVE} call on {@link #sharedModelBuilderSession}, which still
- * benefits from the {@code mappedSources} populated during the reactor build.</p>
- *
- * @param context the upgrade context (used for debug logging)
- * @param pomPath the path to the POM file
- * @return the effective model, never {@code null}
- */
- protected Model buildEffectiveModel(UpgradeContext context, Path pomPath) {
- Path key = pomPath.toAbsolutePath().normalize();
-
- // Fast path: reactor pre-build already has this model.
- Map<Path, Model> cache = effectiveModelCache;
- if (cache != null) {
- Model cached = cache.get(key);
- if (cached != null) {
- context.debug("Effective model cache hit: " + pomPath);
- return cached;
- }
+ protected void cleanupTempDirectory(Path tempDir) {
+ try {
+ Files.walk(tempDir)
Review Comment:
**[medium] `Files.walk()` stream not closed — filesystem handle leak**
`Files.walk()` returns a `Stream<Path>` that holds an open directory handle until closed. The current code never closes it: if `forEach` throws (e.g. `SecurityException` from `File::delete`) the stream stays open until GC. In the previous code deleted by this PR, `AbstractUpgradeStrategyTest` used `try (var walk = Files.walk(...))` correctly — that pattern should be followed here.
```suggestion
protected void cleanupTempDirectory(Path tempDir) {
try (var walk = Files.walk(tempDir)) {
walk.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (Exception e) {
// Best effort cleanup
}
}
```
##########
impl/maven-core/src/test/java/org/apache/maven/project/MavenProjectGetArtifactsTest.java:
##########
@@ -1,87 +0,0 @@
-/*
- * 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.project;
-
-import java.util.ArrayList;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.LockSupport;
-
-import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.DefaultArtifact;
-import org.junit.jupiter.api.Test;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-class MavenProjectGetArtifactsTest {
-
- @Test
- void concurrentGetArtifactsDoesNotExposeAHalfBuiltSet() throws Exception {
- MavenProject project = new MavenProject();
- Set<Artifact> resolved = new LinkedHashSet<>();
- for (int i = 0; i < 200; i++) {
- resolved.add(new DefaultArtifact("g", "a" + i, "1", "compile", "jar", "", null));
- }
- project.setResolvedArtifacts(resolved);
- project.setArtifactFilter(artifact -> {
- LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(50));
- return true;
- });
-
- int readers = 4;
- ExecutorService pool = Executors.newFixedThreadPool(readers);
- CountDownLatch start = new CountDownLatch(1);
- List<Future<?>> futures = new ArrayList<>();
- try {
- for (int i = 0; i < readers; i++) {
- futures.add(pool.submit(() -> {
- start.await();
- Set<Artifact> artifacts = project.getArtifacts();
- assertEquals(resolved.size(), artifacts.size());
- AtomicInteger seen = new AtomicInteger();
- artifacts.forEach(artifact -> seen.incrementAndGet());
- assertEquals(resolved.size(), seen.get());
- return null;
- }));
- }
- start.countDown();
- for (Future<?> future : futures) {
- try {
- future.get(30, TimeUnit.SECONDS);
- } catch (ExecutionException e) {
- throw e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
- }
- }
- } finally {
- pool.shutdownNow();
- }
-
- assertFalse(project.getArtifacts().isEmpty());
- assertEquals(resolved.size(), project.getArtifacts().size());
- }
-}
Review Comment:
**[medium] Concurrency regression test deleted without replacement**
This file is deleted by the PR, but the concurrency fix it covers (`MavenProject.getArtifacts()` — restore `result` local variable so `artifacts` is only assigned after the loop completes) is still present in the production code. Deleting the test removes the guard against this regression being reintroduced silently. The test should either be retained as-is (it's a clean, self-contained stress test) or ported into a different test class, but not simply deleted.
Note that `MavenProject.artifacts` is still non-`volatile` and `getArtifacts()` is still unsynchronized — the `result` local variable prevents observers from seeing a half-populated set *during construction*, but two threads that both see `artifacts == null` will still both enter the if-block and both compute the set. Whether that's acceptable depends on the broader threading model of `MavenProject`, but the test at minimum ensures the final state is consistent.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4079618800
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/AbstractUpgradeStrategy.java:
##########
@@ -424,55 +318,29 @@ protected Path findCommonRoot(Set<Path> pomPaths) {
return commonRoot;
}
- /**
- * Returns the effective model for the given POM path.
- *
- * <p>Consults {@link #effectiveModelCache} first (populated by the {@code BUILD_PROJECT}
- * reactor pass in {@link #prebuildReactorModels}). If the path is not in the cache
- * (e.g. an external parent that was not part of the reactor), falls back to a
- * {@code BUILD_EFFECTIVE} call on {@link #sharedModelBuilderSession}, which still
- * benefits from the {@code mappedSources} populated during the reactor build.</p>
- *
- * @param context the upgrade context (used for debug logging)
- * @param pomPath the path to the POM file
- * @return the effective model, never {@code null}
- */
- protected Model buildEffectiveModel(UpgradeContext context, Path pomPath) {
- Path key = pomPath.toAbsolutePath().normalize();
-
- // Fast path: reactor pre-build already has this model.
- Map<Path, Model> cache = effectiveModelCache;
- if (cache != null) {
- Model cached = cache.get(key);
- if (cached != null) {
- context.debug("Effective model cache hit: " + pomPath);
- return cached;
- }
+ protected void cleanupTempDirectory(Path tempDir) {
+ try {
+ Files.walk(tempDir)
Review Comment:
Resolved: the temporary directory approach was removed entirely in the squash commit `abd26c76a9` ("feat: logging foundation"). `PluginUpgradeStrategy` now builds effective models directly from the on-disk POMs — no temp copy, no `cleanupTempDirectory`, no `Files.walk` stream.
##########
impl/maven-core/src/test/java/org/apache/maven/project/MavenProjectGetArtifactsTest.java:
##########
@@ -1,87 +0,0 @@
-/*
- * 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.project;
-
-import java.util.ArrayList;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.LockSupport;
-
-import org.apache.maven.artifact.Artifact;
-import org.apache.maven.artifact.DefaultArtifact;
-import org.junit.jupiter.api.Test;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-
-class MavenProjectGetArtifactsTest {
-
- @Test
- void concurrentGetArtifactsDoesNotExposeAHalfBuiltSet() throws Exception {
- MavenProject project = new MavenProject();
- Set<Artifact> resolved = new LinkedHashSet<>();
- for (int i = 0; i < 200; i++) {
- resolved.add(new DefaultArtifact("g", "a" + i, "1", "compile", "jar", "", null));
- }
- project.setResolvedArtifacts(resolved);
- project.setArtifactFilter(artifact -> {
- LockSupport.parkNanos(TimeUnit.MICROSECONDS.toNanos(50));
- return true;
- });
-
- int readers = 4;
- ExecutorService pool = Executors.newFixedThreadPool(readers);
- CountDownLatch start = new CountDownLatch(1);
- List<Future<?>> futures = new ArrayList<>();
- try {
- for (int i = 0; i < readers; i++) {
- futures.add(pool.submit(() -> {
- start.await();
- Set<Artifact> artifacts = project.getArtifacts();
- assertEquals(resolved.size(), artifacts.size());
- AtomicInteger seen = new AtomicInteger();
- artifacts.forEach(artifact -> seen.incrementAndGet());
- assertEquals(resolved.size(), seen.get());
- return null;
- }));
- }
- start.countDown();
- for (Future<?> future : futures) {
- try {
- future.get(30, TimeUnit.SECONDS);
- } catch (ExecutionException e) {
- throw e.getCause() instanceof Exception ? (Exception) e.getCause() : e;
- }
- }
- } finally {
- pool.shutdownNow();
- }
-
- assertFalse(project.getArtifacts().isEmpty());
- assertEquals(resolved.size(), project.getArtifacts().size());
- }
-}
Review Comment:
Resolved: `MavenProjectGetArtifactsTest` is present in the current branch at `impl/maven-core/src/test/java/org/apache/maven/project/MavenProjectGetArtifactsTest.java`. It was restored in the squash commit `abd26c76a9`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "ascheman (via GitHub)" <gi...@apache.org>.
ascheman commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3752792431
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -36,13 +36,62 @@
@Experimental
@Provider
public interface Log {
+ /**
+ * {@return true if the <b>trace</b> error level is enabled}
+ * @since 4.1.0
+ */
+ boolean isTraceEnabled();
Review Comment:
The six new `trace` methods (`isTraceEnabled` + 5 overloads) are abstract, while `child(String)` below ships with a `default`. Any existing third-party implementor of `Log` breaks — source and binary (`AbstractMethodError`) — on `trace`, but not on `child`. `Log` is `@Experimental`, so it's arguably in-bounds for 4.1.0, but the asymmetry looks unintentional. Could the `trace` methods get backward-compatible defaults — `isTraceEnabled()` returning `false` and the `trace(…)` overloads as no-ops — so existing implementations keep compiling and opt in by overriding? (`DefaultLog` overrides all of it, so the runtime path is unchanged.)
##########
impl/maven-core/src/main/java/org/apache/maven/logging/ProjectBuildLogAppender.java:
##########
@@ -52,6 +72,31 @@ public static void setProjectId(String projectId) {
}
}
+ public static String getMojoId() {
+ return MOJO_ID.get();
+ }
+
+ /**
+ * Sets or clears the mojo execution identifier in both the thread-local
+ * and the SLF4J MDC. The value is available to any SLF4J appender via
+ * the MDC key {@code maven.mojo.id} and to JUL-bridged messages through
+ * the same MDC path.
+ * <p>
+ * Format: {@code "prefix:goal@executionId"}
+ * (e.g. {@code "compiler:compile@default-compile"}).
+ *
+ * @param mojoId the mojo identifier, or {@code null} to clear
+ */
+ public static void setMojoId(String mojoId) {
Review Comment:
Project id has a fork-aware restore via `FORKING_PROJECT_ID` (consulted in `getProjectId()`), but mojo id doesn't: `mojoSucceeded`/`mojoFailed` in `LoggingExecutionListener` call `setMojoId(null)`, so when a forking mojo (e.g. a report goal that forks a lifecycle) resumes after its fork completes, `maven.mojo.id` has been cleared and is never restored — subsequent log lines from the forking mojo lose their MDC attribution. Should there be a symmetric `FORKING_MOJO_ID` (or a save/restore around the fork) mirroring the project-id handling?
Related: `MOJO_ID` is an `InheritableThreadLocal`; with reused pool threads a value not cleared on an exceptional path could inherit into a later, unrelated task.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,167 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
+ */
+ @Nullable
+ default String sourceMethodName() {
+ return null;
+ }
+
+ /**
+ * The thread identifier from which this log event originated.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ * @since 4.1.0
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @return the sequence number, always non-negative
+ * @since 4.1.0
+ */
+ default long sequenceNumber() {
Review Comment:
`sequenceNumber()` javadoc says "always non-negative," but the default returns `-1` and `DefaultLogEvent` passes `-1` when unknown. Fix the doc (or the sentinel) so they agree.
##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java:
##########
@@ -18,149 +18,251 @@
*/
package org.apache.maven.internal.impl;
+import java.lang.StackWalker.StackFrame;
import java.util.function.Supplier;
import org.apache.maven.api.plugin.Log;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
public class DefaultLog implements Log {
+
+ /**
+ * Metadata captured from Log API calls, mirroring the JUL metadata
+ * pattern in {@code MavenJulHandler}.
+ *
+ * @param sourceClassName the fully qualified class name of the caller
+ * @param sourceMethodName the method that issued the log call
+ * @param threadId the originating thread ID
+ */
+ public record LogApiMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<LogApiMetadata> LOG_API_METADATA = new ThreadLocal<>();
+ private static final StackWalker WALKER = StackWalker.getInstance();
+ private static final String THIS_CLASS = DefaultLog.class.getName();
+
+ /**
+ * Returns the Log API metadata for the current log event being processed,
+ * or {@code null} if the current event did not originate from the Log API.
+ * <p>
+ * Called from {@code ProjectBuildLogAppender.accept()} to populate
+ * {@code LogEvent.sourceClassName()} and {@code LogEvent.sourceMethodName()}.
+ *
+ * @return the current Log API metadata, or {@code null}
+ */
+ public static LogApiMetadata getLogApiMetadata() {
+ return LOG_API_METADATA.get();
+ }
+
private final Logger logger;
public DefaultLog(Logger logger) {
this.logger = requireNonNull(logger);
}
+ /**
+ * Wraps a logging call with Log API metadata: captures the caller's
+ * method name via {@link StackWalker}, sets the ThreadLocal, executes
+ * the actual SLF4J call, and clears the ThreadLocal.
+ * <p>
+ * The source class name is taken from the SLF4J logger name (which
+ * is the mojo implementation FQCN, set at injection time). The
+ * source method name is resolved by walking the stack past this class
+ * to find the first external caller frame.
+ */
+ private void withMetadata(Runnable logAction) {
Review Comment:
`withMetadata` runs a `StackWalker.walk(…)` on every *enabled* Log-API call to recover the caller method name. The `isXxxEnabled()` guards mean disabled levels are free, but INFO-level logging in a loop now pays a stack-walk per call. Worth a quick benchmark; alternatively make the source-method capture lazy/opt-in, since most appenders won't render it.
Minor, same method: `Thread.currentThread().getId()` is deprecated since Java 19 (`Thread.threadId()`), and the JUL path already uses the modern `getLongThreadID()` — aligning them would be consistent.
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -70,15 +101,74 @@ protected String renderLevel(int level) {
}
@Override
- protected void write(StringBuilder buf, Throwable t) {
- Consumer<String> sink = logSink;
+ protected void write(int level, String loggerName, String cleanMessage, StringBuilder formattedBuf, Throwable t) {
+ LogSink sink = logSink;
if (sink != null) {
- sink.accept(buf.toString());
+ // Build the full formatted output including throwable rendering
+ String formatted = formattedBuf.toString();
if (t != null) {
- writeThrowable(t, sink);
+ StringBuilder full = new StringBuilder(formatted);
+ full.append(System.lineSeparator());
+ appendFormattedThrowable(full, t, "");
Review Comment:
The new `LogSink` path hand-rolls throwable rendering (`appendFormattedThrowable`/`appendStackTrace`) while the non-sink path still goes through `super.write(…)` → `writeThrowable`. Two throwable renderings that can drift over time — could the sink path reuse the existing `writeThrowable`/`printStackTrace` (which still take `Consumer<String>`) to keep them single-sourced? Relatedly, `MavenJulHandler.formatForConsole` emits a bare `"[LEVEL] message"` that won't match this class's console layout, so JUL-origin lines look different from native lines on the sink path.
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.apache.maven.api.services.MessageBuilder;
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.apache.maven.jline.MessageUtils.builder;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * When a {@link MavenSimpleLogger.LogSink LogSink} is installed (i.e. during
+ * a build), JUL events are sent directly to the sink — bypassing SLF4J
+ * entirely. The JUL metadata is stashed in a thread-local so downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * When no LogSink is installed (e.g. during early bootstrap), the handler
+ * falls back to routing through SLF4J for console output.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Returns the JUL metadata for the current log event being processed,
+ * or {@code null} if the current log event did not originate from JUL.
+ * <p>
+ * This method is intended to be called from within a
+ * {@link MavenSimpleLogger.LogSink} callback (e.g. in
+ * {@code ProjectBuildLogAppender.accept()}).
+ *
+ * @return the current JUL metadata, or {@code null}
+ */
+ public static JulMetadata getJulMetadata() {
+ return METADATA.get();
+ }
+
+ /**
+ * Installs this handler on the JUL root logger, removing any
+ * previously installed handlers. This replaces the standard
+ * {@code SLF4JBridgeHandler.install()} call.
+ */
+ public static void install() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ // Remove all existing handlers (including any SLF4JBridgeHandler)
+ for (Handler handler : rootLogger.getHandlers()) {
+ rootLogger.removeHandler(handler);
+ }
+ rootLogger.addHandler(new MavenJulHandler());
+ // Accept all levels — filtering is done by SLF4J
+ rootLogger.setLevel(Level.ALL);
+ }
+
+ /**
+ * Returns {@code true} if a {@code MavenJulHandler} is installed
+ * on the JUL root logger.
+ */
+ public static boolean isInstalled() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ for (Handler handler : rootLogger.getHandlers()) {
+ if (handler instanceof MavenJulHandler) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void publish(LogRecord record) {
+ if (record == null) {
+ return;
+ }
+
+ String loggerName = record.getLoggerName();
+ org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(loggerName);
Review Comment:
`record.getLoggerName()` can be `null` per the JUL spec; it's passed straight to `LoggerFactory.getLogger(loggerName)`. Worth confirming that resolves to the root logger across SLF4J bindings rather than producing a literally `"null"`-named logger.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046245795
##########
impl/maven-logging/src/test/java/org/apache/maven/slf4j/MavenJulHandlerTest.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.slf4j;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Tests for {@link MavenJulHandler}, focused on the JUL→SLF4J level
+ * mapping and metadata lifecycle.
+ */
+class MavenJulHandlerTest {
+
+ /**
+ * Table test for JUL level → SLF4J level mapping.
+ * Verifies the mapping documented in the class Javadoc.
+ */
+ @ParameterizedTest(name = "JUL {0} -> SLF4J level {1}")
+ @CsvSource({
+ "FINEST, 0", // TRACE_INT = 0
+ "FINER, 10", // DEBUG_INT = 10
+ "FINE, 10", // DEBUG_INT = 10
+ "CONFIG, 20", // INFO_INT = 20
+ "INFO, 20", // INFO_INT = 20
+ "WARNING, 30", // WARN_INT = 30
+ "SEVERE, 40", // ERROR_INT = 40
+ })
+ void julLevelMapsToCorrectSlf4jLevel(String julLevelName, int expectedSlf4jLevel) throws Exception {
+ Level julLevel = Level.parse(julLevelName);
+ int actual = invokeJulLevelToSlf4j(julLevel);
+ assertEquals(
+ expectedSlf4jLevel, actual, "JUL " + julLevelName + " should map to SLF4J level " + expectedSlf4jLevel);
+ }
+
+ /**
+ * Verify that FINEST maps to TRACE (not DEBUG) — this is the key
+ * distinction for the TRACE/DEBUG separation.
+ */
+ @Test
+ void finestMapsToTrace() throws Exception {
+ assertEquals(
+ LocationAwareLogger.TRACE_INT,
+ invokeJulLevelToSlf4j(Level.FINEST),
+ "FINEST should map to TRACE, not DEBUG");
+ }
+
+ /**
+ * Verify that CONFIG maps to INFO (not DEBUG) — CONFIG is JUL's
+ * informational level for static configuration, not a debug level.
+ */
+ @Test
+ void configMapsToInfo() throws Exception {
+ assertEquals(LocationAwareLogger.INFO_INT, invokeJulLevelToSlf4j(Level.CONFIG), "CONFIG should map to INFO");
+ }
+
+ /**
+ * Verify that JUL metadata is null when no log event is being processed.
+ */
+ @Test
+ void julMetadataIsNullOutsidePublish() {
+ assertNull(MavenJulHandler.getJulMetadata(), "JUL metadata should be null outside a publish() call");
+ }
+
+ /**
+ * Verify that a recursive call to {@link MavenJulHandler#publish} from
+ * within a {@code publish()} call on the same thread is silently dropped
+ * instead of crashing with {@code IllegalStateException("Recursive update")}.
+ * <p>
+ * This is the reentrancy scenario that occurs when JLine's
+ * {@code StyleResolver} logs a JUL DEBUG event while
+ * {@code MavenSimpleLogger.renderLevel()} is lazily initialising ANSI
+ * colour strings during terminal construction.
+ */
+ @Test
+ void publishIsReentrantSafe() throws Exception {
+ MavenJulHandler handler = new MavenJulHandler();
+ java.util.logging.LogRecord outerRecord = new java.util.logging.LogRecord(Level.INFO, "outer");
+
+ // Install a custom SLF4J logger that fires a second JUL event
Review Comment:
Fixed in 222071d770: replaced the misleading comment with: "Simulate re-entrance: set IN_PUBLISH=true before calling publish(). The reentrancy guard should short-circuit without throwing or logging."
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4012507615
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -332,6 +332,16 @@ protected final void createTerminal(C context) {
ProjectBuildLogAppender projectBuildLogAppender =
new ProjectBuildLogAppender(determineBuildEventListener(context));
context.closeables.add(projectBuildLogAppender);
+
+ // Now that the logSink (and any -l log-file writer) is installed,
+ // replay early log messages that were accumulated before
+ // activateLogging() ran. This ensures messages such as
+ // "Enabled to break the build on log level WARN." reach the log
+ // file rather than stdout (MavenITmng6065 regression fix).
+ if (context.pendingEarlyLogs != null) {
+ context.pendingEarlyLogs.forEach(e -> context.logger.log(e.level(), e.message(), e.error()));
+ context.pendingEarlyLogs = null;
Review Comment:
**[high] `pendingEarlyLogs` drain is dead code — `activateLogging()` has not run yet when this executes**
`doInvoke()` calls `createTerminal()` at line 159, then `activateLogging()` at line 160. The drain block below executes at the end of `createTerminal()`, but `context.pendingEarlyLogs` is set by `activateLogging()` (line 518), which hasn't been called yet. So `context.pendingEarlyLogs` is always `null` here, the `if` branch is never taken, and the MavenITmng6065 fix (early messages reaching the log file) is completely non-functional.
The fix has two correct options:
**Option A** — move the drain to the start of `activateLogging()` *after* installing `ProjectBuildLogAppender` (but that's the wrong place since the appender is installed in `createTerminal()`).
**Option B** — move the drain call to occur *after* `activateLogging()` returns, i.e. call it from `doInvoke()` directly:
```java
protected int doInvoke(C context) throws Exception {
...
configureLogging(context);
createTerminal(context); // installs ProjectBuildLogAppender / logSink
activateLogging(context); // sets context.pendingEarlyLogs
// Now that both the logSink AND pendingEarlyLogs are set, drain:
if (context.pendingEarlyLogs != null) {
context.pendingEarlyLogs.forEach(e -> context.logger.log(e.level(), e.message(), e.error()));
context.pendingEarlyLogs = null;
}
helpOrVersionAndMayExit(context);
...
}
```
The drain block currently in `createTerminal()` should be removed.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -87,8 +87,6 @@ default void trace(Throwable error) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
*/
default void trace(Supplier<String> content) {}
Review Comment:
**[low] Missing `@param content` tag — inconsistent with all other overloads**
The diff removes `@param content the message supplier` from `trace(Supplier<String> content)`. Every other supplier-based method in this interface (`debug`, `info`, `warn`, `error`) retains its `@param content` and `@param error` tags. The removal makes the Javadoc incomplete and inconsistent.
```suggestion
/**
* Sends a lazily-computed message at the <b>trace</b> error level.
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility
* with existing {@code Log} implementations.
*
* @param content the message supplier
*/
default void trace(Supplier<String> content) {}
```
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -97,9 +95,6 @@ default void trace(Supplier<String> content) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
- * @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
Review Comment:
**[low] Missing `@param content` and `@param error` tags — inconsistent with all other overloads**
Same issue: the diff removes both `@param` tags from `trace(Supplier<String>, Throwable)`. Every other supplier+throwable method in this interface documents both parameters.
```suggestion
/**
* Sends a lazily-computed message (and accompanying exception) at the <b>trace</b> error level.
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility
* with existing {@code Log} implementations.
*
* @param content the message supplier
* @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057929168
##########
impl/maven-core/src/main/resources/org/apache/maven/lifecycle/plugin-versions.properties:
##########
@@ -17,19 +17,19 @@
# Default lifecycle plugin versions.
# Values are substituted by Maven resource filtering at build time from
-# POM properties (lifecycle.<name>-plugin), making them visible to
+# POM properties (version.maven-<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
-lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
-lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
-lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
-lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
-lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
-lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
-lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
-lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
-lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
-lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
-lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
-lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
-lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
+version.maven-clean-plugin=${version.maven-clean-plugin}
Review Comment:
Fixed in cbc1d608db: restored master's lifecycle plugin versions across all 13 properties.
##########
impl/maven-core/src/main/resources/org/apache/maven/lifecycle/plugin-versions.properties:
##########
@@ -17,19 +17,19 @@
# Default lifecycle plugin versions.
# Values are substituted by Maven resource filtering at build time from
-# POM properties (lifecycle.<name>-plugin), making them visible to
+# POM properties (version.maven-<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
-lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
-lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
-lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
-lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
-lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
-lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
-lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
-lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
-lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
-lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
-lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
-lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
-lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
+version.maven-clean-plugin=${version.maven-clean-plugin}
+version.maven-compiler-plugin=${version.maven-compiler-plugin}
+version.maven-deploy-plugin=${version.maven-deploy-plugin}
+version.maven-ear-plugin=${version.maven-ear-plugin}
+version.maven-ejb-plugin=${version.maven-ejb-plugin}
+version.maven-install-plugin=${version.maven-install-plugin}
+version.maven-jar-plugin=${version.maven-jar-plugin}
+version.maven-plugin-plugin=${version.maven-plugin-plugin}
+version.maven-rar-plugin=${version.maven-rar-plugin}
+version.maven-resources-plugin=${version.maven-resources-plugin}
+version.maven-site-plugin=${version.maven-site-plugin}
+version.maven-surefire-plugin=${version.maven-surefire-plugin}
+version.maven-war-plugin=${version.maven-war-plugin}
Review Comment:
Fixed in cbc1d608db: restored master's lifecycle plugin versions across all 13 properties.
##########
impl/maven-core/src/main/resources/org/apache/maven/lifecycle/plugin-versions.properties:
##########
@@ -17,19 +17,19 @@
# Default lifecycle plugin versions.
# Values are substituted by Maven resource filtering at build time from
-# POM properties (lifecycle.<name>-plugin), making them visible to
+# POM properties (version.maven-<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
-lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
-lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
-lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
-lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
-lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
-lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
-lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
-lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
-lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
-lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
-lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
-lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
-lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
+version.maven-clean-plugin=${version.maven-clean-plugin}
+version.maven-compiler-plugin=${version.maven-compiler-plugin}
+version.maven-deploy-plugin=${version.maven-deploy-plugin}
+version.maven-ear-plugin=${version.maven-ear-plugin}
+version.maven-ejb-plugin=${version.maven-ejb-plugin}
Review Comment:
Fixed in cbc1d608db: restored master's lifecycle plugin versions across all 13 properties.
##########
impl/maven-core/pom.xml:
##########
@@ -36,19 +36,19 @@ under the License.
Maintained here so that dependency-update bots (Dependabot, Renovate)
can propose version bumps automatically. Values are filtered into
plugin-versions.properties at build time and loaded at runtime. -->
- <lifecycle.maven-clean-plugin>3.4.0</lifecycle.maven-clean-plugin>
- <lifecycle.maven-compiler-plugin>3.13.0</lifecycle.maven-compiler-plugin>
- <lifecycle.maven-deploy-plugin>3.1.3</lifecycle.maven-deploy-plugin>
- <lifecycle.maven-ear-plugin>3.3.0</lifecycle.maven-ear-plugin>
- <lifecycle.maven-ejb-plugin>3.2.1</lifecycle.maven-ejb-plugin>
- <lifecycle.maven-install-plugin>3.1.3</lifecycle.maven-install-plugin>
- <lifecycle.maven-jar-plugin>3.4.2</lifecycle.maven-jar-plugin>
- <lifecycle.maven-plugin-plugin>3.15.1</lifecycle.maven-plugin-plugin>
- <lifecycle.maven-rar-plugin>3.0.0</lifecycle.maven-rar-plugin>
- <lifecycle.maven-resources-plugin>3.3.1</lifecycle.maven-resources-plugin>
- <lifecycle.maven-site-plugin>3.21.0</lifecycle.maven-site-plugin>
- <lifecycle.maven-surefire-plugin>3.5.2</lifecycle.maven-surefire-plugin>
- <lifecycle.maven-war-plugin>3.4.0</lifecycle.maven-war-plugin>
+ <lifecycle.maven-clean-plugin>3.5.0</lifecycle.maven-clean-plugin>
+ <lifecycle.maven-compiler-plugin>3.16.0</lifecycle.maven-compiler-plugin>
+ <lifecycle.maven-deploy-plugin>3.2.0</lifecycle.maven-deploy-plugin>
+ <lifecycle.maven-ear-plugin>3.4.0</lifecycle.maven-ear-plugin>
+ <lifecycle.maven-ejb-plugin>3.3.0</lifecycle.maven-ejb-plugin>
+ <lifecycle.maven-install-plugin>3.2.0</lifecycle.maven-install-plugin>
+ <lifecycle.maven-jar-plugin>3.5.1</lifecycle.maven-jar-plugin>
+ <lifecycle.maven-plugin-plugin>3.16.0</lifecycle.maven-plugin-plugin>
+ <lifecycle.maven-rar-plugin>3.1.0</lifecycle.maven-rar-plugin>
+ <lifecycle.maven-resources-plugin>3.5.0</lifecycle.maven-resources-plugin>
+ <lifecycle.maven-site-plugin>3.22.0</lifecycle.maven-site-plugin>
+ <lifecycle.maven-surefire-plugin>3.6.0</lifecycle.maven-surefire-plugin>
+ <lifecycle.maven-war-plugin>3.5.1</lifecycle.maven-war-plugin>
Review Comment:
Fixed in cbc1d608db: restored master's lifecycle plugin versions across all 13 properties.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #12694:
URL: https://github.com/apache/maven/pull/12694#issuecomment-5752284645
Fixed in `cbc1d608db` + `bbff94a91c`: restored master's lifecycle plugin versions (all 13 `lifecycle.maven-*-plugin` properties updated to match current master) and aligned the pluginManagement comment text. The three files (`pom.xml`, `plugin-versions.properties`, `PluginVersions.java`) now match master exactly.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3879510044
##########
impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java:
##########
@@ -18,149 +18,251 @@
*/
package org.apache.maven.internal.impl;
+import java.lang.StackWalker.StackFrame;
import java.util.function.Supplier;
import org.apache.maven.api.plugin.Log;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import static java.util.Objects.requireNonNull;
public class DefaultLog implements Log {
+
+ /**
+ * Metadata captured from Log API calls, mirroring the JUL metadata
+ * pattern in {@code MavenJulHandler}.
+ *
+ * @param sourceClassName the fully qualified class name of the caller
+ * @param sourceMethodName the method that issued the log call
+ * @param threadId the originating thread ID
+ */
+ public record LogApiMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<LogApiMetadata> LOG_API_METADATA = new ThreadLocal<>();
+ private static final StackWalker WALKER = StackWalker.getInstance();
+ private static final String THIS_CLASS = DefaultLog.class.getName();
+
+ /**
+ * Returns the Log API metadata for the current log event being processed,
+ * or {@code null} if the current event did not originate from the Log API.
+ * <p>
+ * Called from {@code ProjectBuildLogAppender.accept()} to populate
+ * {@code LogEvent.sourceClassName()} and {@code LogEvent.sourceMethodName()}.
+ *
+ * @return the current Log API metadata, or {@code null}
+ */
+ public static LogApiMetadata getLogApiMetadata() {
+ return LOG_API_METADATA.get();
+ }
+
private final Logger logger;
public DefaultLog(Logger logger) {
this.logger = requireNonNull(logger);
}
+ /**
+ * Wraps a logging call with Log API metadata: captures the caller's
+ * method name via {@link StackWalker}, sets the ThreadLocal, executes
+ * the actual SLF4J call, and clears the ThreadLocal.
+ * <p>
+ * The source class name is taken from the SLF4J logger name (which
+ * is the mojo implementation FQCN, set at injection time). The
+ * source method name is resolved by walking the stack past this class
+ * to find the first external caller frame.
+ */
+ private void withMetadata(Runnable logAction) {
Review Comment:
Fixed — StackWalker is now conditional: `if (ProjectBuildLogAppender.hasReportCapture())` before walking. The ~1-5μs per-call cost is only paid when build report capture is actually active. During normal builds, `withMetadata()` just sets the ThreadLocal with the logger name and thread ID (no stack walking).
##########
impl/maven-core/src/main/java/org/apache/maven/logging/ProjectBuildLogAppender.java:
##########
@@ -52,6 +72,31 @@ public static void setProjectId(String projectId) {
}
}
+ public static String getMojoId() {
+ return MOJO_ID.get();
+ }
+
+ /**
+ * Sets or clears the mojo execution identifier in both the thread-local
+ * and the SLF4J MDC. The value is available to any SLF4J appender via
+ * the MDC key {@code maven.mojo.id} and to JUL-bridged messages through
+ * the same MDC path.
+ * <p>
+ * Format: {@code "prefix:goal@executionId"}
+ * (e.g. {@code "compiler:compile@default-compile"}).
+ *
+ * @param mojoId the mojo identifier, or {@code null} to clear
+ */
+ public static void setMojoId(String mojoId) {
Review Comment:
Fixed — added `FORKING_MOJO_ID` ThreadLocal mirroring the existing `FORKING_PROJECT_ID` pattern. `LoggingExecutionListener.forkStarted()` saves the current mojoId via `setForkingMojoId()`, and `forkSucceeded()`/`forkFailed()` clear it. Also fixed the cleanup ordering: `setMojoId(null)` now runs *after* `delegate.mojoSucceeded`/`mojoFailed` so the mojo context is available during the delegate callback, and `setMojoId(null)` restores the forking mojo's ID if one was saved.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4012352892
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +457,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
Review Comment:
**[medium] Quiet-mode JUL root level should be `SEVERE`, not `WARNING`** (carried over from previous review — still unaddressed)
In quiet mode Maven sets SLF4J to `ERROR` level (`Slf4jConfiguration.Level.ERROR`, line 296). The stated goal of this JUL root level assignment is to suppress events **at source** so that newly-created SLF4J loggers (briefly at `INFO` before propagation) don't leak output. But `Level.WARNING` (integer 900) blocks only `INFO`/`DEBUG`/`FINE` JUL events — `WARNING`-and-above events still pass the root filter and reach `MavenJulHandler.publish()`. During the race window where a new SLF4J logger hasn't had `ERROR` propagated yet, a JUL `WARNING` event will slip through `isLevelEnabled()` (which sees `INFO`) and appear on console — exactly the flakiness pattern this is trying to fix.
`Level.SEVERE` (integer 1000) is the correct JUL equivalent of SLF4J `ERROR`. Update the code and the comment above:
```suggestion
julRootLevel = java.util.logging.Level.SEVERE;
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048556144
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
**[low] Javadoc copy-paste: `@return` says "the formatted message" but this is `message()`, not `formattedMessage()`.**
The field comment says "The log message, without level prefix or timestamp formatting" — the `@return` tag should match:
```suggestion
* @return the log message, never {@code null}
```
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
**[low] Trivially-true assertion — doesn't test the `finally { remove() }` path.**
`ProjectBuildLogAppender.hasReportCapture()` returns `false` in unit tests (no capture installed), so `withMetadata()` takes the `else` branch:
```java
} else {
logAction.run();
}
```
`LOG_API_METADATA.set()` is never called → the ThreadLocal was never populated → `assertNull` trivially passes regardless of whether the `finally { remove() }` block is present or correct.
To actually exercise the cleanup path, install a no-op capture before the call:
```java
void logApiMetadataIsClearedAfterCall() {
Logger mockLogger = mock(Logger.class);
when(mockLogger.isInfoEnabled()).thenReturn(true);
when(mockLogger.getName()).thenReturn("com.example.MyMojo");
// Install a capture so hasReportCapture() returns true,
// forcing withMetadata() through the set/walk/remove path
ProjectBuildLogAppender appender = mock(ProjectBuildLogAppender.class);
ProjectBuildLogAppender.setInstance(appender);
try {
DefaultLog log = new DefaultLog(mockLogger);
log.info("test message");
assertNull(DefaultLog.getLogApiMetadata(),
"LOG_API_METADATA must be removed in the finally block");
} finally {
ProjectBuildLogAppender.setInstance(null);
}
}
```
(Exact API depends on how `ProjectBuildLogAppender` exposes its capture flag — adapt accordingly.)
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub) via issues" <is...@maven.apache.org>.
gnodet closed pull request #12694: Logging foundation: structured LogEvent, JUL handler, Log API enhancements
URL: https://github.com/apache/maven/pull/12694
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #12694:
URL: https://github.com/apache/maven/pull/12694#issuecomment-6360192196
@rmannibucau Thanks for the review — good design feedback. Addressed inline on each specific point. Summary of what I'll act on:
1. **`formattedMessage()` on the interface** → agreed it's a rendering concern, not data. Will remove from `LogEvent` interface and move to an injected `LogEventFormatter` in consumers (coordinating with #13180 before this becomes a shipped API).
2. **`Throwable` vs pre-formatted `stackTrace()`** → will add `default @Nullable Throwable throwable()` alongside `stackTrace()` for consumers that need the raw exception.
3. **Thread name capture** → will add `threadName()` populated at event-creation time in both `MavenJulHandler` and `ProjectBuildLogAppender`.
4. **Custom `LogManager` guard in `LookupInvoker`** → will add the guard (matching `SLF4JBridgeHandler`'s own defense) before touching JUL root handlers.
5. **`message()` as template+args** → keeping as substituted string for now (JUL path can't reconstruct the template after formatting); explained rationale inline.
6. **"Why not full JUL/LogRecord"** → Maven is SLF4J-first; routing SLF4J events through JUL would add overhead and lose marker/MDC data. Explained inline.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057750125
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: changed `@return the formatted message, never {@code null}` to `@return the log message, never {@code null}` in `LogEvent.message()`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: changed `@return the formatted message, never {@code null}` to `@return the log message, never {@code null}` in `LogEvent.message()`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: changed `@return the formatted message, never {@code null}` to `@return the log message, never {@code null}` in `LogEvent.message()`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: changed `@return the formatted message, never {@code null}` to `@return the log message, never {@code null}` in `LogEvent.message()`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: changed `@return the formatted message, never {@code null}` to `@return the log message, never {@code null}` in `LogEvent.message()`.
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: the test now calls `ProjectBuildLogAppender.setReportCapture(event -> {})` before `log.info()` to activate the metadata code path, ensuring the `finally { LOG_API_METADATA.remove() }` block is actually exercised. Capture is cleared in a `finally` block to avoid leaking across tests.
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: the test now calls `ProjectBuildLogAppender.setReportCapture(event -> {})` before `log.info()` to activate the metadata code path, ensuring the `finally { LOG_API_METADATA.remove() }` block is actually exercised. Capture is cleared in a `finally` block to avoid leaking across tests.
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: the test now calls `ProjectBuildLogAppender.setReportCapture(event -> {})` before `log.info()` to activate the metadata code path, ensuring the `finally { LOG_API_METADATA.remove() }` block is actually exercised. Capture is cleared in a `finally` block to avoid leaking across tests.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057975199
##########
impl/maven-logging/src/test/java/org/apache/maven/slf4j/MavenJulHandlerTest.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.slf4j;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Tests for {@link MavenJulHandler}, focused on the JUL→SLF4J level
+ * mapping and metadata lifecycle.
+ */
+class MavenJulHandlerTest {
+
+ /**
+ * Table test for JUL level → SLF4J level mapping.
+ * Verifies the mapping documented in the class Javadoc.
+ */
+ @ParameterizedTest(name = "JUL {0} -> SLF4J level {1}")
+ @CsvSource({
+ "FINEST, 0", // TRACE_INT = 0
+ "FINER, 10", // DEBUG_INT = 10
+ "FINE, 10", // DEBUG_INT = 10
+ "CONFIG, 20", // INFO_INT = 20
+ "INFO, 20", // INFO_INT = 20
+ "WARNING, 30", // WARN_INT = 30
+ "SEVERE, 40", // ERROR_INT = 40
+ })
+ void julLevelMapsToCorrectSlf4jLevel(String julLevelName, int expectedSlf4jLevel) throws Exception {
+ Level julLevel = Level.parse(julLevelName);
+ int actual = invokeJulLevelToSlf4j(julLevel);
+ assertEquals(
+ expectedSlf4jLevel, actual, "JUL " + julLevelName + " should map to SLF4J level " + expectedSlf4jLevel);
+ }
+
+ /**
+ * Verify that FINEST maps to TRACE (not DEBUG) — this is the key
+ * distinction for the TRACE/DEBUG separation.
+ */
+ @Test
+ void finestMapsToTrace() throws Exception {
+ assertEquals(
+ LocationAwareLogger.TRACE_INT,
+ invokeJulLevelToSlf4j(Level.FINEST),
+ "FINEST should map to TRACE, not DEBUG");
+ }
+
+ /**
+ * Verify that CONFIG maps to INFO (not DEBUG) — CONFIG is JUL's
+ * informational level for static configuration, not a debug level.
+ */
+ @Test
+ void configMapsToInfo() throws Exception {
+ assertEquals(LocationAwareLogger.INFO_INT, invokeJulLevelToSlf4j(Level.CONFIG), "CONFIG should map to INFO");
+ }
+
+ /**
+ * Verify that JUL metadata is null when no log event is being processed.
+ */
+ @Test
+ void julMetadataIsNullOutsidePublish() {
+ assertNull(MavenJulHandler.getJulMetadata(), "JUL metadata should be null outside a publish() call");
+ }
+
+ /**
+ * Verify that a recursive call to {@link MavenJulHandler#publish} from
+ * within a {@code publish()} call on the same thread is silently dropped
+ * instead of crashing with {@code IllegalStateException("Recursive update")}.
+ * <p>
+ * This is the reentrancy scenario that occurs when JLine's
+ * {@code StyleResolver} logs a JUL DEBUG event while
+ * {@code MavenSimpleLogger.renderLevel()} is lazily initialising ANSI
+ * colour strings during terminal construction.
+ */
+ @Test
+ void publishIsReentrantSafe() throws Exception {
+ MavenJulHandler handler = new MavenJulHandler();
+ java.util.logging.LogRecord outerRecord = new java.util.logging.LogRecord(Level.INFO, "outer");
+
+ // Simulate re-entrance: set IN_PUBLISH=true before calling publish().
+ // The reentrancy guard should short-circuit without throwing or logging.
+ java.util.logging.Logger julLogger =
+ java.util.logging.LogManager.getLogManager().getLogger("");
+ java.util.logging.Handler[] saved = julLogger.getHandlers();
+ for (java.util.logging.Handler h : saved) {
+ julLogger.removeHandler(h);
+ }
+
+ // The test verifies that publish() does not throw.
+ // We can't easily simulate the full SLF4J pipeline here, so we just
+ // call publish() with a null-logger-name record (which returns early
+ // before reaching SLF4J) after setting IN_PUBLISH to true, verifying
+ // the guard works.
+ java.lang.reflect.Field inPublishField = MavenJulHandler.class.getDeclaredField("IN_PUBLISH");
+ inPublishField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ ThreadLocal<Boolean> inPublish = (ThreadLocal<Boolean>) inPublishField.get(null);
+
+ // Simulate being inside publish()
+ inPublish.set(Boolean.TRUE);
+ try {
+ // A nested call should be dropped without throwing
+ handler.publish(outerRecord);
+ // If we reach here, the guard worked correctly
+ } finally {
+ inPublish.remove();
+ // Restore handlers
+ for (java.util.logging.Handler h : saved) {
+ julLogger.addHandler(h);
+ }
+ }
Review Comment:
Fixed in b0a1155e82: added a package-private `setInPublishForTest(boolean)` method to `MavenJulHandler` so the test no longer needs reflection to access `IN_PUBLISH`. The unnecessary JUL root-handler save/restore noise is also removed — it was unrelated to the guard check.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357373813
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the log message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
You're right that JUL's `LogRecord` does carry the template (`getMessage()`) and params (`getParameters()`) separately — I misspoke. The constraint is on the SLF4J path: by the time `MavenBaseLogger.innerHandleNormalizedLoggingCall()` fires, SLF4J has already formatted the message via `MessageFormatter.arrayFormat()` and the original template is gone (it's not passed down from the caller to the internal handler).
Reversing the direction (making `LogEvent` the first-class abstraction and deriving SLF4J/JUL calls from it) would be a larger architectural change — it would mean building Maven's own logging API before delegating to SLF4J, rather than the current approach of intercepting at the SLF4J provider level. That's a valid design but it's out of scope for this PR.
For now I'll keep `message()` as the post-substitution string (it's consistent across all three input paths), and we can revisit the template/args question separately if there's a concrete use case that needs them.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
Review Comment:
Fair point — dropping the serialization requirement and keeping it async-friendly by eagerly materializing lazy fields is a cleaner contract. I'll add a default `@Nullable Throwable throwable()` method to the interface, populated from `LogRecord.getThrown()` on the JUL path and from the SLF4J `ILoggingEvent` throwable proxy on the SLF4J path. The existing `stackTrace()` string stays for cases where the original `Throwable` isn't available (e.g. events deserialized from a report).
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4009614691
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +447,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
Review Comment:
**[medium] JUL quiet level should be `SEVERE`, not `WARNING`**
In quiet mode, SLF4J is configured at `ERROR` level. The stated goal of the JUL root level assignment is to suppress events *at source* so that the brief window where newly-created SLF4J loggers are still at their default `INFO` level doesn't leak output. Using `Level.WARNING` only blocks `INFO`/`DEBUG`/`FINE` JUL events — `WARNING` events (JUL integer value 900) still pass the root filter and reach `MavenJulHandler.publish()`. Inside `publish()`, they hit `isLevelEnabled()`, which during that brief race window may see the SLF4J logger at `INFO` (not yet propagated to `ERROR`), allowing the `WARNING` event through to the console — exactly the flakiness pattern this fix is trying to prevent.
`Level.SEVERE` (integer value 1000) is the JUL equivalent of SLF4J `ERROR` and matches the quiet-mode intent precisely: only `SEVERE`-and-above JUL events pass the root filter.
```suggestion
julRootLevel = java.util.logging.Level.SEVERE;
```
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +447,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
+ } else if (context.invokerRequest.effectiveVerbose()) {
+ julRootLevel = java.util.logging.Level.ALL;
+ } else {
+ julRootLevel = java.util.logging.Level.INFO;
+ }
+ java.util.logging.LogManager.getLogManager().getLogger("").setLevel(julRootLevel);
Review Comment:
**[low] Update comment to reference `SEVERE` instead of `WARNING`**
If `Level.SEVERE` is adopted above, the comment on line 460 ("keep JUL root at WARNING") should be updated to say `SEVERE` to stay accurate.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4079537516
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,318 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * All JUL events are routed through SLF4J so that {@link MavenSimpleLogger}
+ * produces a consistent {@code formattedMessage} (with timestamp, logger name,
+ * and ANSI styling) regardless of the event's origin. The JUL metadata is
+ * stashed in a thread-local <em>before</em> the SLF4J call so that downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Private SLF4J logger cache using {@link ConcurrentMap#putIfAbsent}
+ * instead of {@link ConcurrentMap#computeIfAbsent}. This avoids the
+ * {@code ConcurrentHashMap.computeIfAbsent} reentrancy bug
+ * ({@code IllegalStateException("Recursive update")}) that occurs
+ * when a JUL event fires during SLF4J logger initialization: the
+ * handler's {@code publish()} calls {@code LoggerFactory.getLogger()},
+ * which internally uses {@code computeIfAbsent}, and if that triggers
+ * another JUL event whose logger name hashes to the same bucket,
+ * {@code ConcurrentHashMap} throws. {@code putIfAbsent} is safe
+ * against reentrancy — worst case, two threads create the same
+ * logger and one is discarded.
+ */
+ private static final ConcurrentMap<String, org.slf4j.Logger> LOGGER_CACHE = new ConcurrentHashMap<>();
+
Review Comment:
**[low] `LOGGER_CACHE` grows unbounded — potential memory pressure in long-running daemon processes.**
`LOGGER_CACHE` is a `static final ConcurrentHashMap` with no eviction. In a Maven daemon that runs hundreds of builds, JUL-emitting frameworks with many named loggers (e.g. Netty, gRPC, Hibernate in complex builds) will populate this cache indefinitely. Each entry is small (string key + SLF4J logger wrapper), but it can accumulate.
Not blocking for an initial implementation, but worth a bounded `LinkedHashMap`-based LRU or a note in the Javadoc that the cache is intentionally unbounded (size bounded by distinct JUL logger names seen across all builds in the daemon process). Post-MVP cleanup candidate.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057964158
##########
impl/maven-logging/src/test/java/org/apache/maven/slf4j/MavenJulHandlerTest.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.slf4j;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Tests for {@link MavenJulHandler}, focused on the JUL→SLF4J level
+ * mapping and metadata lifecycle.
+ */
+class MavenJulHandlerTest {
+
+ /**
+ * Table test for JUL level → SLF4J level mapping.
+ * Verifies the mapping documented in the class Javadoc.
+ */
+ @ParameterizedTest(name = "JUL {0} -> SLF4J level {1}")
+ @CsvSource({
+ "FINEST, 0", // TRACE_INT = 0
+ "FINER, 10", // DEBUG_INT = 10
+ "FINE, 10", // DEBUG_INT = 10
+ "CONFIG, 20", // INFO_INT = 20
+ "INFO, 20", // INFO_INT = 20
+ "WARNING, 30", // WARN_INT = 30
+ "SEVERE, 40", // ERROR_INT = 40
+ })
+ void julLevelMapsToCorrectSlf4jLevel(String julLevelName, int expectedSlf4jLevel) throws Exception {
+ Level julLevel = Level.parse(julLevelName);
+ int actual = invokeJulLevelToSlf4j(julLevel);
+ assertEquals(
+ expectedSlf4jLevel, actual, "JUL " + julLevelName + " should map to SLF4J level " + expectedSlf4jLevel);
+ }
+
+ /**
+ * Verify that FINEST maps to TRACE (not DEBUG) — this is the key
+ * distinction for the TRACE/DEBUG separation.
+ */
+ @Test
+ void finestMapsToTrace() throws Exception {
+ assertEquals(
+ LocationAwareLogger.TRACE_INT,
+ invokeJulLevelToSlf4j(Level.FINEST),
+ "FINEST should map to TRACE, not DEBUG");
+ }
+
+ /**
+ * Verify that CONFIG maps to INFO (not DEBUG) — CONFIG is JUL's
+ * informational level for static configuration, not a debug level.
+ */
+ @Test
+ void configMapsToInfo() throws Exception {
+ assertEquals(LocationAwareLogger.INFO_INT, invokeJulLevelToSlf4j(Level.CONFIG), "CONFIG should map to INFO");
+ }
+
+ /**
+ * Verify that JUL metadata is null when no log event is being processed.
+ */
+ @Test
+ void julMetadataIsNullOutsidePublish() {
+ assertNull(MavenJulHandler.getJulMetadata(), "JUL metadata should be null outside a publish() call");
+ }
+
+ /**
+ * Verify that a recursive call to {@link MavenJulHandler#publish} from
+ * within a {@code publish()} call on the same thread is silently dropped
+ * instead of crashing with {@code IllegalStateException("Recursive update")}.
+ * <p>
+ * This is the reentrancy scenario that occurs when JLine's
+ * {@code StyleResolver} logs a JUL DEBUG event while
+ * {@code MavenSimpleLogger.renderLevel()} is lazily initialising ANSI
+ * colour strings during terminal construction.
+ */
+ @Test
+ void publishIsReentrantSafe() throws Exception {
+ MavenJulHandler handler = new MavenJulHandler();
+ java.util.logging.LogRecord outerRecord = new java.util.logging.LogRecord(Level.INFO, "outer");
+
+ // Simulate re-entrance: set IN_PUBLISH=true before calling publish().
+ // The reentrancy guard should short-circuit without throwing or logging.
+ java.util.logging.Logger julLogger =
+ java.util.logging.LogManager.getLogManager().getLogger("");
+ java.util.logging.Handler[] saved = julLogger.getHandlers();
+ for (java.util.logging.Handler h : saved) {
+ julLogger.removeHandler(h);
+ }
+
+ // The test verifies that publish() does not throw.
+ // We can't easily simulate the full SLF4J pipeline here, so we just
+ // call publish() with a null-logger-name record (which returns early
+ // before reaching SLF4J) after setting IN_PUBLISH to true, verifying
+ // the guard works.
+ java.lang.reflect.Field inPublishField = MavenJulHandler.class.getDeclaredField("IN_PUBLISH");
+ inPublishField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ ThreadLocal<Boolean> inPublish = (ThreadLocal<Boolean>) inPublishField.get(null);
+
+ // Simulate being inside publish()
+ inPublish.set(Boolean.TRUE);
+ try {
+ // A nested call should be dropped without throwing
+ handler.publish(outerRecord);
+ // If we reach here, the guard worked correctly
+ } finally {
+ inPublish.remove();
+ // Restore handlers
+ for (java.util.logging.Handler h : saved) {
+ julLogger.addHandler(h);
+ }
+ }
Review Comment:
**[low] `publishIsReentrantSafe()` simulates reentrancy via reflection but doesn't exercise the real crash path**
The test accesses `IN_PUBLISH` via `getDeclaredField("IN_PUBLISH")` and pre-sets it to `true`, then calls `publish()` which returns early at the reentrancy check. This verifies the guard's early-return branch, but not the *actual crash scenario*: `MavenSimpleLogger.renderLevel()` calling `StyleResolver.resolve()` → `ConcurrentHashMap.computeIfAbsent` reentrancy.
Using reflection ties the test to the private field name and ThreadLocal type — renaming `IN_PUBLISH` silently breaks the test with an `NoSuchFieldException` instead of a compile error. The test also removes JUL root handlers unnecessarily (they aren't involved in the guard check path).
A simpler and more honest test would install `MavenJulHandler` as the only handler, then fire a JUL event from within an SLF4J Logger callback that itself fires a JUL event — but that requires a real SLF4J binding. Alternatively, expose a package-private `setReentrancyGuardForTest()` test hook so the test doesn't need reflection.
This is low priority given the production fix is correct, but the test's coverage claim in its Javadoc is stronger than what it actually exercises.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3879513429
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,167 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.Nullable;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
+ */
+ @Nullable
+ default String sourceMethodName() {
+ return null;
+ }
+
+ /**
+ * The thread identifier from which this log event originated.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ * @since 4.1.0
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @return the sequence number, always non-negative
+ * @since 4.1.0
+ */
+ default long sequenceNumber() {
Review Comment:
Fixed (same as @gnodet's comment above) — javadoc now reads `@return the sequence number, or {@code -1} if unavailable`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #12694:
URL: https://github.com/apache/maven/pull/12694#issuecomment-5450880020
## Review feedback addressed
All 8 review comments from @gnodet and @ascheman have been addressed in the latest force-push. Summary of changes:
### Bug fixes
- **`sequenceNumber()` javadoc** — corrected from "always non-negative" to "or `-1` if unavailable"
- **`warn(Supplier, Throwable)` regression** — was calling `logger.info()` instead of `logger.warn()` (added regression test)
### Design improvements
- **`MavenJulHandler` simplified** — removed `formatForConsole()` entirely; all JUL events now always route through SLF4J so `MavenSimpleLogger` produces a consistent `formattedMessage` regardless of origin
- **`Log.trace()` backward compatibility** — all 6 trace methods changed from `abstract` to `default` implementations (no-ops) to prevent `AbstractMethodError` for existing third-party `Log` implementors
- **StackWalker gated** — `withMetadata()` only walks the stack when `ProjectBuildLogAppender.hasReportCapture()` is true; normal builds pay zero StackWalker cost
- **Fork-aware mojoId** — added `FORKING_MOJO_ID` ThreadLocal mirroring `FORKING_PROJECT_ID`; `forkStarted()`/`forkSucceeded()`/`forkFailed()` save and restore mojo context
- **Throwable rendering unified** — `MavenSimpleLogger.write()` now reuses the existing `writeThrowable()` method; removed the duplicate `appendFormattedThrowable()`/`appendStackTrace()` methods
- **Null `loggerName` guard** — `MavenJulHandler.publish()` now handles `null` logger names per JUL spec
### Tests added
- `DefaultLogTest` (4 tests): warn/supplier regression, metadata lifecycle, trace delegation, trace no-op
- `MavenJulHandlerTest` (10 tests): parameterized JUL→SLF4J level mapping, FINEST→TRACE, CONFIG→INFO, metadata null check
All 6 downstream PRs (#12695, #12697, #12698, #12699, #12702, #12714) have been rebased onto the updated commit.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357350532
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the log message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
dont we consider it from the opposite window?
the log event is the abstraction with template/args (whatever format works) then we pass it to slf4j/jul as needed? we also know how to map one to the other so think it can benefit the overall API even if it means getting plugged in all layers no?
I'm not sure the JUL point, getMessage is the template and getParameters the parameters no?
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357411702
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
Good question. exists because Maven is the SLF4J **provider** (not a consumer): it implements and supplies its own . That gives us control over every log call made by plugins and Maven itself — we can intercept at the source, before any formatting happens, and route to directly.
If we used an off-the-shelf SLF4J backend (Logback, Log4j2, the simple logger shipped with SLF4J) we'd have to either (a) configure it externally and lose the ability to swap the sink at runtime, or (b) write our own backend anyway — which is exactly what / are.
Long term the goal is for to do less: once the plugin / extension SPI converges on (maven-api-core), internal Maven code will use it directly, and can shrink to a thin SLF4J bridge. But that migration is a separate concern and happens incrementally across the PR chain — worth opening a follow-up issue if you'd like to track it.
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
Good question. `MavenSimpleLogger` exists because Maven is the SLF4J **provider** (not a consumer): it implements `org.slf4j.spi.SLF4JServiceProvider` and supplies its own `ILoggerFactory`. That gives us control over every log call made by plugins and Maven itself — we can intercept at the source, before any formatting happens, and route to `LogSink.accept()` directly.
If we used an off-the-shelf SLF4J backend (Logback, Log4j2, the simple logger shipped with SLF4J) we'd have to either (a) configure it externally and lose the ability to swap the sink at runtime, or (b) write our own backend anyway — which is exactly what `MavenSimpleLogger`/`MavenBaseLogger` are.
Long term the goal is for `MavenSimpleLogger` to do less: once the plugin / extension SPI converges on `Log` (maven-api-core), internal Maven code will use it directly, and `MavenSimpleLogger` can shrink to a thin SLF4J bridge. But that migration is a separate concern and happens incrementally across the PR chain — worth opening a follow-up issue if you'd like to track it.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046253895
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -87,8 +87,6 @@ default void trace(Throwable error) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
*/
default void trace(Supplier<String> content) {}
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -97,9 +95,6 @@ default void trace(Supplier<String> content) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
- * @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +457,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
+ } else if (context.invokerRequest.effectiveVerbose()) {
+ julRootLevel = java.util.logging.Level.ALL;
+ } else {
+ julRootLevel = java.util.logging.Level.INFO;
+ }
+ java.util.logging.LogManager.getLogManager().getLogger("").setLevel(julRootLevel);
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
##########
impl/maven-logging/src/test/java/org/apache/maven/slf4j/MavenJulHandlerTest.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.slf4j;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Tests for {@link MavenJulHandler}, focused on the JUL→SLF4J level
+ * mapping and metadata lifecycle.
+ */
+class MavenJulHandlerTest {
+
+ /**
+ * Table test for JUL level → SLF4J level mapping.
+ * Verifies the mapping documented in the class Javadoc.
+ */
+ @ParameterizedTest(name = "JUL {0} -> SLF4J level {1}")
+ @CsvSource({
+ "FINEST, 0", // TRACE_INT = 0
+ "FINER, 10", // DEBUG_INT = 10
+ "FINE, 10", // DEBUG_INT = 10
+ "CONFIG, 20", // INFO_INT = 20
+ "INFO, 20", // INFO_INT = 20
+ "WARNING, 30", // WARN_INT = 30
+ "SEVERE, 40", // ERROR_INT = 40
+ })
+ void julLevelMapsToCorrectSlf4jLevel(String julLevelName, int expectedSlf4jLevel) throws Exception {
+ Level julLevel = Level.parse(julLevelName);
+ int actual = invokeJulLevelToSlf4j(julLevel);
+ assertEquals(
+ expectedSlf4jLevel, actual, "JUL " + julLevelName + " should map to SLF4J level " + expectedSlf4jLevel);
+ }
+
+ /**
+ * Verify that FINEST maps to TRACE (not DEBUG) — this is the key
+ * distinction for the TRACE/DEBUG separation.
+ */
+ @Test
+ void finestMapsToTrace() throws Exception {
+ assertEquals(
+ LocationAwareLogger.TRACE_INT,
+ invokeJulLevelToSlf4j(Level.FINEST),
+ "FINEST should map to TRACE, not DEBUG");
+ }
+
+ /**
+ * Verify that CONFIG maps to INFO (not DEBUG) — CONFIG is JUL's
+ * informational level for static configuration, not a debug level.
+ */
+ @Test
+ void configMapsToInfo() throws Exception {
+ assertEquals(LocationAwareLogger.INFO_INT, invokeJulLevelToSlf4j(Level.CONFIG), "CONFIG should map to INFO");
+ }
+
+ /**
+ * Verify that JUL metadata is null when no log event is being processed.
+ */
+ @Test
+ void julMetadataIsNullOutsidePublish() {
+ assertNull(MavenJulHandler.getJulMetadata(), "JUL metadata should be null outside a publish() call");
+ }
+
+ /**
+ * Verify that a recursive call to {@link MavenJulHandler#publish} from
+ * within a {@code publish()} call on the same thread is silently dropped
+ * instead of crashing with {@code IllegalStateException("Recursive update")}.
+ * <p>
+ * This is the reentrancy scenario that occurs when JLine's
+ * {@code StyleResolver} logs a JUL DEBUG event while
+ * {@code MavenSimpleLogger.renderLevel()} is lazily initialising ANSI
+ * colour strings during terminal construction.
+ */
+ @Test
+ void publishIsReentrantSafe() throws Exception {
+ MavenJulHandler handler = new MavenJulHandler();
+ java.util.logging.LogRecord outerRecord = new java.util.logging.LogRecord(Level.INFO, "outer");
+
+ // Install a custom SLF4J logger that fires a second JUL event
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4047348344
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @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}
+ * @since 4.1.0
Review Comment:
**[low] Redundant `@since 4.1.0`** — the interface itself is `@since 4.1.0` (line 43). A method-level `@since` on a method added in the same version as the interface implies the method was added after the interface, which is misleading. Same issue on `mojoId()` below. Drop these tags, or add `@since 4.1.0` consistently on every method in the interface.
```suggestion
/**
* 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}
*/
```
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
Review Comment:
**[low] Same — redundant `@since 4.1.0`**.
```suggestion
/**
* 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}
*/
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046244547
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -87,8 +87,6 @@ default void trace(Throwable error) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
*/
default void trace(Supplier<String> content) {}
Review Comment:
Fixed in 222071d770: restored `@param content` tag on `trace(Supplier<String> content)`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -97,9 +95,6 @@ default void trace(Supplier<String> content) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
- * @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
Review Comment:
Fixed in 222071d770: restored both `@param content` and `@param error` tags on `trace(Supplier<String> content, Throwable error)`.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +457,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
+ } else if (context.invokerRequest.effectiveVerbose()) {
+ julRootLevel = java.util.logging.Level.ALL;
+ } else {
+ julRootLevel = java.util.logging.Level.INFO;
+ }
+ java.util.logging.LogManager.getLogManager().getLogger("").setLevel(julRootLevel);
Review Comment:
Fixed in 222071d770: changed `Level.WARNING` to `Level.SEVERE` in quiet mode. Updated the comment to explain that SEVERE matches the SLF4J ERROR threshold exactly, suppressing both INFO and WARNING JUL events at source during the race window.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048577406
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
**[low] `logApiMetadataIsClearedAfterCall()` is trivially true — never exercises the cleanup path**
The test calls `log.info("test message")` without setting `reportCapture`. Inside `withMetadata()`, the guard `ProjectBuildLogAppender.hasReportCapture()` returns `false`, so the method takes the `else` branch and calls `logAction.run()` directly — the `LOG_API_METADATA` ThreadLocal is **never set**. `assertNull(getLogApiMetadata())` therefore passes trivially regardless of whether the `finally { LOG_API_METADATA.remove(); }` block is correct.
To actually test the cleanup, `reportCapture` must be set before the call (so `hasReportCapture()` returns `true`) and cleared afterward:
```suggestion
ProjectBuildLogAppender.setReportCapture(event -> {});
try {
log.info("test message");
} finally {
ProjectBuildLogAppender.setReportCapture(null);
}
// After the call completes, metadata should be cleared
assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057891656
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * All JUL events are routed through SLF4J so that {@link MavenSimpleLogger}
+ * produces a consistent {@code formattedMessage} (with timestamp, logger name,
+ * and ANSI styling) regardless of the event's origin. The JUL metadata is
+ * stashed in a thread-local <em>before</em> the SLF4J call so that downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Private SLF4J logger cache using {@link ConcurrentMap#putIfAbsent}
+ * instead of {@link ConcurrentMap#computeIfAbsent}. This avoids the
+ * {@code ConcurrentHashMap.computeIfAbsent} reentrancy bug
+ * ({@code IllegalStateException("Recursive update")}) that occurs
+ * when a JUL event fires during SLF4J logger initialization: the
+ * handler's {@code publish()} calls {@code LoggerFactory.getLogger()},
+ * which internally uses {@code computeIfAbsent}, and if that triggers
+ * another JUL event whose logger name hashes to the same bucket,
+ * {@code ConcurrentHashMap} throws. {@code putIfAbsent} is safe
+ * against reentrancy — worst case, two threads create the same
+ * logger and one is discarded.
+ */
+ private static final ConcurrentMap<String, org.slf4j.Logger> LOGGER_CACHE = new ConcurrentHashMap<>();
+
+ /**
+ * Re-entrancy guard: set to {@code true} while {@link #publish} is routing
+ * a JUL event through SLF4J on this thread. Prevents recursive JUL events
+ * (e.g. JLine's {@code StyleResolver} calling {@code java.util.logging.Logger}
+ * while inside {@link MavenSimpleLogger#renderLevel} lazy-initialisation,
+ * which in turn is triggered by a JUL event during terminal construction)
+ * from re-entering {@code publish} and crashing with
+ * {@code ConcurrentHashMap.computeIfAbsent IllegalStateException("Recursive update")}.
+ */
+ private static final ThreadLocal<Boolean> IN_PUBLISH = new ThreadLocal<>();
+
+ /**
+ * Returns the JUL metadata for the current log event being processed,
+ * or {@code null} if the current log event did not originate from JUL.
+ * <p>
+ * This method is intended to be called from within a
+ * {@link MavenSimpleLogger.LogSink} callback (e.g. in
+ * {@code ProjectBuildLogAppender.accept()}).
+ *
+ * @return the current JUL metadata, or {@code null}
+ */
+ public static JulMetadata getJulMetadata() {
+ return METADATA.get();
+ }
+
+ /**
+ * Installs this handler on the JUL root logger, removing any
+ * previously installed handlers. This replaces the standard
+ * {@code SLF4JBridgeHandler.install()} call.
+ */
+ public static void install() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ // Remove all existing handlers (including any SLF4JBridgeHandler)
+ for (Handler handler : rootLogger.getHandlers()) {
+ rootLogger.removeHandler(handler);
+ }
+ rootLogger.addHandler(new MavenJulHandler());
+ // Note: we intentionally do NOT set rootLogger.setLevel(Level.ALL)
+ // here. Setting it eagerly floods JUL events during SLF4J bootstrap,
+ // triggering ConcurrentHashMap.computeIfAbsent reentrancy in the
+ // SLF4J logger factory ("Recursive update"). The JUL root default
+ // (INFO) is fine — callers that need FINE/FINEST events (e.g. -X
+ // debug mode) should set the JUL root level after SLF4J is fully
+ // initialized.
+ }
+
+ /**
+ * Returns {@code true} if a {@code MavenJulHandler} is installed
+ * on the JUL root logger.
+ */
+ public static boolean isInstalled() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ for (Handler handler : rootLogger.getHandlers()) {
+ if (handler instanceof MavenJulHandler) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void publish(LogRecord record) {
Review Comment:
Fixed in bfafd94fd3 — added `isLoggable(record)` check immediately after the null guard, before the reentrancy guard.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048663883
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
**[low] Javadoc copy-paste: `@return` says "the formatted message" but this is `message()`, not `formattedMessage()`.**
The field comment says "The log message, without level prefix or timestamp formatting" — the `@return` tag should match:
```suggestion
* @return the log message, never {@code null}
```
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
**[low] `logApiMetadataIsClearedAfterCall()` is trivially true — never exercises the cleanup path**
The test calls `log.info("test message")` without activating report capture. Inside `withMetadata()`, `ProjectBuildLogAppender.hasReportCapture()` returns `false`, so it takes the `else` branch and calls `logAction.run()` directly — `LOG_API_METADATA.set()` and `.remove()` are never called. `assertNull(getLogApiMetadata())` is always true whether or not the `finally { remove() }` block works.
To actually test the cleanup path, activate capture before the call:
```java
ProjectBuildLogAppender.setReportCapture(consumer -> {});
try {
log.info("test message");
assertNull(DefaultLog.getLogApiMetadata(), "ThreadLocal must be cleared after call");
} finally {
ProjectBuildLogAppender.setReportCapture(null);
}
```
Or use a `@TempDir`-based `MockBuildEventListener` if that's how capture is activated in tests.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4012554468
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -332,6 +332,16 @@ protected final void createTerminal(C context) {
ProjectBuildLogAppender projectBuildLogAppender =
new ProjectBuildLogAppender(determineBuildEventListener(context));
context.closeables.add(projectBuildLogAppender);
+
+ // Now that the logSink (and any -l log-file writer) is installed,
+ // replay early log messages that were accumulated before
+ // activateLogging() ran. This ensures messages such as
+ // "Enabled to break the build on log level WARN." reach the log
+ // file rather than stdout (MavenITmng6065 regression fix).
+ if (context.pendingEarlyLogs != null) {
+ context.pendingEarlyLogs.forEach(e -> context.logger.log(e.level(), e.message(), e.error()));
+ context.pendingEarlyLogs = null;
Review Comment:
Fixed in 63ed04e. Moved the drain into `activateLogging()` (after the `context.logger.drain()` / logger swap), where `createTerminal()` has already installed `ProjectBuildLogAppender`. The dead drain block in `createTerminal()` has been removed, and the `pendingEarlyLogs` field in `LookupContext` is gone too.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -87,8 +87,6 @@ default void trace(Throwable error) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
*/
default void trace(Supplier<String> content) {}
Review Comment:
Fixed in 63ed04e. Added `@param content the message supplier` to the Javadoc for `trace(Supplier<String>)`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -97,9 +95,6 @@ default void trace(Supplier<String> content) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
- * @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
Review Comment:
Fixed in 63ed04e. Added both `@param content the message supplier` and `@param error the error that caused this log` to the Javadoc for `trace(Supplier<String>, Throwable)`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3879508255
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.apache.maven.api.services.MessageBuilder;
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.apache.maven.jline.MessageUtils.builder;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * When a {@link MavenSimpleLogger.LogSink LogSink} is installed (i.e. during
+ * a build), JUL events are sent directly to the sink — bypassing SLF4J
+ * entirely. The JUL metadata is stashed in a thread-local so downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * When no LogSink is installed (e.g. during early bootstrap), the handler
+ * falls back to routing through SLF4J for console output.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Returns the JUL metadata for the current log event being processed,
+ * or {@code null} if the current log event did not originate from JUL.
+ * <p>
+ * This method is intended to be called from within a
+ * {@link MavenSimpleLogger.LogSink} callback (e.g. in
+ * {@code ProjectBuildLogAppender.accept()}).
+ *
+ * @return the current JUL metadata, or {@code null}
+ */
+ public static JulMetadata getJulMetadata() {
+ return METADATA.get();
+ }
+
+ /**
+ * Installs this handler on the JUL root logger, removing any
+ * previously installed handlers. This replaces the standard
+ * {@code SLF4JBridgeHandler.install()} call.
+ */
+ public static void install() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ // Remove all existing handlers (including any SLF4JBridgeHandler)
+ for (Handler handler : rootLogger.getHandlers()) {
+ rootLogger.removeHandler(handler);
+ }
+ rootLogger.addHandler(new MavenJulHandler());
+ // Accept all levels — filtering is done by SLF4J
+ rootLogger.setLevel(Level.ALL);
+ }
+
+ /**
+ * Returns {@code true} if a {@code MavenJulHandler} is installed
+ * on the JUL root logger.
+ */
+ public static boolean isInstalled() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ for (Handler handler : rootLogger.getHandlers()) {
+ if (handler instanceof MavenJulHandler) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void publish(LogRecord record) {
+ if (record == null) {
+ return;
+ }
+
+ String loggerName = record.getLoggerName();
+ org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(loggerName);
+ int slf4jLevel = julLevelToSlf4j(record.getLevel());
+
+ // Quick exit if this level is not enabled
+ if (!isLevelEnabled(slf4jLogger, slf4jLevel)) {
+ return;
+ }
+
+ String message = formatMessage(record);
+ Throwable throwable = record.getThrown();
+
+ // If a LogSink is installed, bypass SLF4J entirely: call the sink
+ // directly with the JUL metadata so no information is lost in transit.
+ MavenSimpleLogger.LogSink sink = MavenSimpleLogger.getLogSink();
+ if (sink != null) {
+ METADATA.set(new JulMetadata(
+ record.getSourceClassName(), record.getSourceMethodName(), record.getLongThreadID()));
+ try {
+ String formatted = formatForConsole(slf4jLevel, message);
+ sink.accept(slf4jLevel, loggerName, message, formatted, throwable);
+ } finally {
+ METADATA.remove();
+ }
+ } else {
+ // No LogSink — fall through to SLF4J for console output
+ logToSlf4j(slf4jLogger, slf4jLevel, message, throwable);
+ }
+ }
+
+ @Override
+ public void flush() {
+ // nothing to flush
+ }
+
+ @Override
+ public void close() throws SecurityException {
+ // nothing to close
+ }
+
+ /**
+ * Formats the log message, applying i18n resource bundle lookup and
+ * {@link MessageFormat} parameter substitution, matching the behavior
+ * of {@code SLF4JBridgeHandler}.
+ */
Review Comment:
Fixed — removed the `formatForConsole()` method entirely. All JUL events now always route through SLF4J so that `MavenSimpleLogger` produces a consistent `formattedMessage` (with timestamp, logger name, and ANSI styling) regardless of origin. The JUL metadata is stashed in a ThreadLocal *before* the SLF4J call so that `ProjectBuildLogAppender` can read it when constructing the `LogEvent`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -36,13 +36,62 @@
@Experimental
@Provider
public interface Log {
+ /**
+ * {@return true if the <b>trace</b> error level is enabled}
+ * @since 4.1.0
+ */
+ boolean isTraceEnabled();
Review Comment:
Fixed — all 6 trace methods (`isTraceEnabled` + 5 overloads) now have `default` implementations: `isTraceEnabled()` returns `false` by default, and all `trace(...)` overloads are no-ops. This prevents `AbstractMethodError` for existing third-party `Log` implementors.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048216192
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
**Javadoc copy-paste:** `@return` says "the formatted message" but this is `message()`, not `formattedMessage()`. Should read "the log message, never `null`".
```suggestion
* @return the log message, never {@code null}
```
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
This assertion is trivially true and proves nothing about the `finally { LOG_API_METADATA.remove() }` path.
Before `log.info("test message")` is called, `ProjectBuildLogAppender.hasReportCapture()` returns `false` (no capture installed). `withMetadata()` therefore takes the `else` branch:
```java
} else {
logAction.run(); // metadata never touched
}
```
`LOG_API_METADATA` is never set, so `assertNull` always passes — even if the `finally` block were deleted.
To actually test the guarantee, activate capture first:
```java
ProjectBuildLogAppender.setReportCapture(event -> {});
try {
log.info("test message");
assertNull(DefaultLog.getLogApiMetadata(),
"Metadata must be cleared after log call");
} finally {
ProjectBuildLogAppender.setReportCapture(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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4052288758
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted message, never {@code null}
Review Comment:
**[low] `@return` tag copy-pasted from `formattedMessage()` — misleading**
The body says _"without level prefix or timestamp formatting"_ but `@return` says _"the formatted message"_. That's the description of `formattedMessage()`. `message()` is the *clean* message — the contradiction will confuse callers choosing between the two methods.
```suggestion
* @return the log message without level prefix or timestamp, never {@code null}
```
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
**[low] `logApiMetadataIsClearedAfterCall()` doesn't exercise the `remove()` path**
No `reportCapture` callback is set up in this test, so `ProjectBuildLogAppender.hasReportCapture()` returns `false`. `withMetadata()` takes the `else` branch and never touches the ThreadLocal — the assertion `assertNull(getLogApiMetadata())` trivially passes even if the `finally { remove() }` block were deleted.
To actually test the cleanup contract, set a capture callback first:
```java
// Ensure report capture is active so withMetadata() takes the if-branch
ProjectBuildLogAppender.setReportCapture(event -> {});
try {
log.info("test message");
assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
} finally {
ProjectBuildLogAppender.setReportCapture(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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057777122
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,296 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * All JUL events are routed through SLF4J so that {@link MavenSimpleLogger}
+ * produces a consistent {@code formattedMessage} (with timestamp, logger name,
+ * and ANSI styling) regardless of the event's origin. The JUL metadata is
+ * stashed in a thread-local <em>before</em> the SLF4J call so that downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Private SLF4J logger cache using {@link ConcurrentMap#putIfAbsent}
+ * instead of {@link ConcurrentMap#computeIfAbsent}. This avoids the
+ * {@code ConcurrentHashMap.computeIfAbsent} reentrancy bug
+ * ({@code IllegalStateException("Recursive update")}) that occurs
+ * when a JUL event fires during SLF4J logger initialization: the
+ * handler's {@code publish()} calls {@code LoggerFactory.getLogger()},
+ * which internally uses {@code computeIfAbsent}, and if that triggers
+ * another JUL event whose logger name hashes to the same bucket,
+ * {@code ConcurrentHashMap} throws. {@code putIfAbsent} is safe
+ * against reentrancy — worst case, two threads create the same
+ * logger and one is discarded.
+ */
+ private static final ConcurrentMap<String, org.slf4j.Logger> LOGGER_CACHE = new ConcurrentHashMap<>();
+
+ /**
+ * Re-entrancy guard: set to {@code true} while {@link #publish} is routing
+ * a JUL event through SLF4J on this thread. Prevents recursive JUL events
+ * (e.g. JLine's {@code StyleResolver} calling {@code java.util.logging.Logger}
+ * while inside {@link MavenSimpleLogger#renderLevel} lazy-initialisation,
+ * which in turn is triggered by a JUL event during terminal construction)
+ * from re-entering {@code publish} and crashing with
+ * {@code ConcurrentHashMap.computeIfAbsent IllegalStateException("Recursive update")}.
+ */
+ private static final ThreadLocal<Boolean> IN_PUBLISH = new ThreadLocal<>();
+
+ /**
+ * Returns the JUL metadata for the current log event being processed,
+ * or {@code null} if the current log event did not originate from JUL.
+ * <p>
+ * This method is intended to be called from within a
+ * {@link MavenSimpleLogger.LogSink} callback (e.g. in
+ * {@code ProjectBuildLogAppender.accept()}).
+ *
+ * @return the current JUL metadata, or {@code null}
+ */
+ public static JulMetadata getJulMetadata() {
+ return METADATA.get();
+ }
+
+ /**
+ * Installs this handler on the JUL root logger, removing any
+ * previously installed handlers. This replaces the standard
+ * {@code SLF4JBridgeHandler.install()} call.
+ */
+ public static void install() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ // Remove all existing handlers (including any SLF4JBridgeHandler)
+ for (Handler handler : rootLogger.getHandlers()) {
+ rootLogger.removeHandler(handler);
+ }
+ rootLogger.addHandler(new MavenJulHandler());
+ // Note: we intentionally do NOT set rootLogger.setLevel(Level.ALL)
+ // here. Setting it eagerly floods JUL events during SLF4J bootstrap,
+ // triggering ConcurrentHashMap.computeIfAbsent reentrancy in the
+ // SLF4J logger factory ("Recursive update"). The JUL root default
+ // (INFO) is fine — callers that need FINE/FINEST events (e.g. -X
+ // debug mode) should set the JUL root level after SLF4J is fully
+ // initialized.
+ }
+
+ /**
+ * Returns {@code true} if a {@code MavenJulHandler} is installed
+ * on the JUL root logger.
+ */
+ public static boolean isInstalled() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ for (Handler handler : rootLogger.getHandlers()) {
+ if (handler instanceof MavenJulHandler) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void publish(LogRecord record) {
Review Comment:
**[low] `publish()` skips `isLoggable(record)` — violates `Handler` contract**
`java.util.logging.Handler` declares `publish()` implementations responsible for checking `isLoggable(record)` before processing. The standard `SLF4JBridgeHandler` calls it early:
```java
public void publish(LogRecord record) {
if (!isLoggable(record)) {
return;
}
...
}
```
`MavenJulHandler` skips this call entirely, meaning any `Filter` registered on this handler via `setFilter()` is silently ignored. For Maven's own deployment this has zero practical impact (no filter is ever set), but embedders that configure JUL handlers with custom `Filter` objects will find their filters bypassed.
Suggested fix — add the check right after the null guard:
```suggestion
public void publish(LogRecord record) {
if (record == null) {
return;
}
if (!isLoggable(record)) {
return;
}
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057750748
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: the test now calls `ProjectBuildLogAppender.setReportCapture(event -> {})` before `log.info()` to activate the metadata code path, ensuring the `finally { LOG_API_METADATA.remove() }` block is actually exercised. Capture is cleared in a `finally` block to avoid leaking across tests.
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: the test now calls `ProjectBuildLogAppender.setReportCapture(event -> {})` before `log.info()` to activate the metadata code path, ensuring the `finally { LOG_API_METADATA.remove() }` block is actually exercised. Capture is cleared in a `finally` block to avoid leaking across tests.
##########
impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java:
##########
@@ -51,13 +54,31 @@ void warnWithSupplierAndThrowableDelegatesToWarn() {
verify(mockLogger).warn("warning message", ex);
}
+ /**
+ * Verify that Log API metadata is set during the log call and
+ * cleared afterwards — no leakage across calls.
+ */
+ @Test
+ void logApiMetadataIsClearedAfterCall() {
+ Logger mockLogger = mock(Logger.class);
+ when(mockLogger.isInfoEnabled()).thenReturn(true);
+ when(mockLogger.getName()).thenReturn("com.example.MyMojo");
+
+ DefaultLog log = new DefaultLog(mockLogger);
+ log.info("test message");
+
+ // After the call completes, metadata should be cleared
+ assertNull(DefaultLog.getLogApiMetadata(), "Log API metadata should be cleared after the log call");
Review Comment:
Fixed in d7f564ab9dbd8fd1e4f44cb06d13d03d515b08c4: the test now calls `ProjectBuildLogAppender.setReportCapture(event -> {})` before `log.info()` to activate the metadata code path, ensuring the `finally { LOG_API_METADATA.remove() }` block is actually exercised. Capture is cleared in a `finally` block to avoid leaking across tests.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4358073840
##########
impl/maven-core/src/main/java/org/apache/maven/logging/SimpleBuildEventListener.java:
##########
@@ -38,8 +40,16 @@ public void sessionStarted(ExecutionEvent event) {}
public void projectStarted(String projectId) {}
@Override
Review Comment:
💡 **Design note:** `projectLogMessage` now prepends `[WARNING]` / `[INFO]` etc. to the message. The old code forwarded the raw formatted string (which already contained the level prefix from `MavenSimpleLogger`). Please verify this does not double-prefix (e.g. `[WARNING] [WARNING] some message`) when used with the non-JLine (plain) console mode.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357319800
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
Review Comment:
Two competing concerns here:
1. `LogEvent` is designed to be `@Immutable` and serialisable — it will be archived in build reports, exported to JSON, forwarded over IPC. A live `Throwable` reference prevents that; it holds references to class objects, frames, and potentially long chains of causes.
2. JUL's `LogRecord.getThrown()` does carry the raw `Throwable`, but the SLF4J normalization path in `MavenBaseLogger` doesn't always have it at the point of capture, and a bare `Throwable` can't survive serialization if the exception class isn't on the consumer's classpath.
The compromise I had in mind: keep `stackTrace()` as `String` (always available, serializable) and add `default @Nullable Throwable throwable()` for cases where the original is available (JUL path via `LogRecord.getThrown()`). Consumers that need type-based filtering use `throwable()`; pass-through renderers use `stackTrace()`. Would that address your concern?
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
Review Comment:
Agreed. `formattedMessage()` is a rendering concern — it leaks ANSI, level prefix, timestamp into what should be a rendering-agnostic data structure. It's there now because `SimpleBuildEventListener` and PR #13180 (console modes) consume it for pass-through terminal output.
The right fix: remove `formattedMessage()` from the `LogEvent` interface and inject a `LogEventFormatter` (or `Function<LogEvent, String>`) at construction time in the consumers that need it. I'll coordinate with #13180 to ensure the renderer is decoupled before this becomes part of a shipped API. For this PR the method stays for now to unblock the downstream chain, but it should be deprecated-for-removal before 4.1.0 ships.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357318405
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the log message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
Good question. The short answer: there's no consistent template available from all three input paths.
JUL's `LogRecord` does carry `message` + `parameters[]` for `MessageFormat` substitution, but once `MavenJulHandler` calls `Formatter.formatMessage(record)` those two are merged into a single string — there's no going back. SLF4J's `LoggingEvent` does carry the template and args separately (`getMessage()`/`getArgumentArray()`), so we _could_ expose them for SLF4J events, but JUL events would always return `null` args. Consumers would need to branch: check for template → fall back to substituted message, adding complexity for no real gain.
The split between `message()` and `formattedMessage()` serves two different audiences:
- `message()` — raw substituted text, for structured consumers (filters, build reporters, JSON exporters)
- `formattedMessage()` — exactly what the terminal would have printed (level prefix, timestamp, thread, ANSI), for pass-through renderers
That said, I agree that `formattedMessage()` is really a renderer concern and arguably doesn't belong on the event interface. See reply at line 108 for the planned direction.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357324920
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
The fundamental issue is that Maven uses SLF4J as its logging facade — plugins call SLF4J `Logger`, not JUL. The flow is:
- **SLF4J path** (plugins, Maven core): `SLF4J Logger` → `MavenBaseLogger` → `LogSink.accept()` directly, no JUL round-trip. SLF4J MDC, marker, and supplier laziness are preserved.
- **JUL path** (frameworks: Hibernate, Netty, etc.): JUL `Logger.log()` → `MavenJulHandler` (our root handler) → convert to `LogEvent` → `LogSink`.
If we based everything on JUL `LogRecord`, we'd have to route SLF4J events through JUL first — that's the `SLF4JBridgeHandler` direction, which goes the wrong way. We'd pay a round-trip overhead and lose SLF4J marker/MDC metadata that doesn't fit in `LogRecord`'s fixed-shape API.
That said, it's a valid architectural question worth its own discussion thread — if you think there's a cleaner path to unifying around `LogRecord`, I'm happy to explore it. But I'd prefer not to rearchitect during this PR since the downstream chain (#13180, #12695) is already built on the current model.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357260190
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -125,8 +127,10 @@ public final int invoke(InvokerRequest invokerRequest) {
Properties oldProps = new Properties();
oldProps.putAll(System.getProperties());
ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
- // activateLogging() replaces them with SLF4JBridgeHandler, whose classes live in Maven's realm
- Handler[] oldRootLoggerHandlers = java.util.logging.Logger.getLogger("").getHandlers();
+ // activateLogging() replaces them with MavenJulHandler, whose classes live in Maven's realm
Review Comment:
Good catch. Currently the code unconditionally captures the root logger handlers and level, then replaces them with `MavenJulHandler`. If the host JVM has a custom `LogManager` (e.g. an embedded scenario where the parent application uses Log4j2-JUL or a custom manager), we're trampling on it.
The right fix would be:
1. Check `LogManager.getLogManager().getClass() == LogManager.class` (i.e. it's the default implementation) before touching any handlers/levels.
2. If a custom manager is detected, skip the JUL setup entirely and log a debug message saying we're not installing MavenJulHandler because a custom LogManager is active.
This matches what SLF4J's `SLF4JBridgeHandler` does — it bails early when it can't safely manipulate the handler list.
I'll add this guard. The JUL-based log capture in `ProjectBuildLogAppender` would also need to be skipped in that case, since events won't flow through `MavenJulHandler`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357263780
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
Not a dumb question at all — it's actually the most fundamental architectural choice in this PR.
The reason we didn't go pure JUL: Maven already has SLF4J as its logging facade (plugins use `Logger` from SLF4J, not JUL), and the SLF4J→JUL bridge (`SLF4JBridgeHandler`) goes in the wrong direction for our needs. We'd need SLF4J events to flow *into* JUL for `LogRecord` capture, which means reinstalling the bridge, which defeats the purpose.
The current approach goes the other way: we replace the JUL root handler with `MavenJulHandler` so that JUL events from frameworks (Hibernate, Netty, etc.) get captured into our structured `LogEvent` pipeline. SLF4J events flow through `MavenBaseLogger`/`MavenSimpleLogger` which already knows about `LogSink`.
If we based everything on JUL `LogRecord`: we'd need to go SLF4J→JUL→LogRecord, which adds a round-trip and loses some SLF4J marker/MDC information. The current architecture keeps SLF4J events on the fast path (direct `LogSink.accept()` in `MavenBaseLogger`) and uses JUL only as the capture point for non-SLF4J frameworks.
That said: if you think `LogRecord` is the right primitive and we should consolidate everything there, it's a bigger rethink — worth discussing separately. For this PR the goal was to establish the capture pipeline; we can revisit the underlying primitive in a follow-up.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357392481
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
let's reverse the question then, if SLF4J is out impl (ack we don't expose it in the api), then why not using slf4j as impl there and duplicating the model? just trying to reduce the duplication layer, maven simple logger should almost not exist at the end of the rework IMHO and only surface as plugin and extension/services api, not impl bridge, no?
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357258734
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
Review Comment:
That's a fair point. `formattedMessage()` was added as a convenience so that `SimpleBuildEventListener` (and other pass-through console renderers in PR #13180) could just forward the pre-rendered line without re-formatting it. The alternative is to have a `LogEventFormatter` or similar consumer that takes a `LogEvent` and produces the display string.
The downside of keeping it in the API is that the interface leaks a rendering concern (how the line looks on a terminal) into a data structure that's supposed to be rendering-agnostic. You're right that this doesn't belong here.
I'm open to removing it from the interface. The consumer in `SimpleBuildEventListener` would need to carry its own formatting logic (or accept a `Function<LogEvent, String>` formatter). The PR #13180 (console modes) builds on top of this, so I'll coordinate with that PR before removing it — but conceptually I agree with you.
Should I remove it in this PR, or would you prefer a follow-up once we see how #13180 uses it?
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357261730
##########
impl/maven-core/src/main/java/org/apache/maven/internal/build/DefaultLogEvent.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.internal.build;
+
+import java.time.Instant;
+
+import org.apache.maven.api.build.report.LogEvent;
+import org.apache.maven.api.build.report.LogLevel;
+
+/**
+ * Immutable implementation of {@link LogEvent}.
+ * <p>
+ * Public to allow construction from other packages within the Maven
+ * implementation (e.g. {@code ProjectBuildLogAppender}).
+ *
+ * @param timestamp when the event was produced
+ * @param level the severity level
+ * @param message the clean log message (without level prefix or ANSI)
+ * @param loggerName the name of the logger, or {@code null}
+ * @param stackTrace the stack trace string, or {@code null}
+ * @param formattedMessage the fully formatted console line, or {@code null}
+ * @param sourceClassName the source class name (Log API mojo FQCN or JUL source), or {@code null}
+ * @param sourceMethodName the source method name (via StackWalker or JUL), or {@code null}
+ * @param threadId the originating thread ID, or {@code -1} if unavailable
+ * @param sequenceNumber the global sequence number for ordering, or {@code -1} if unavailable
+ * @param projectId the project this event belongs to, or {@code null}
+ * @param mojoId the mojo execution that produced this event, or {@code null}
+ */
+public record DefaultLogEvent(
Review Comment:
You're right that thread name is very useful for consumers — log analysis tools and build reporters want to show it, and reconstructing it after the fact from a thread ID is fragile (the thread might be gone, pooled thread names rotate, etc.).
The reason I didn't include it: `DefaultLogEvent` is a record and `threadId` was already there. Adding `threadName` is straightforward — it's just `Thread.currentThread().getName()` at capture time in `ProjectBuildLogAppender` and `MavenJulHandler` (`LogRecord.getThreadID()` doesn't give us the name, but we can call `Thread.currentThread().getName()` at the same point we capture the ID).
I'll add `threadName()` as a default-null method on the interface and populate it in both capture paths. The only case where it won't be available is events constructed directly in tests or outside the pipeline — same as `threadId()`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357322348
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -125,8 +127,10 @@ public final int invoke(InvokerRequest invokerRequest) {
Properties oldProps = new Properties();
oldProps.putAll(System.getProperties());
ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
- // activateLogging() replaces them with SLF4JBridgeHandler, whose classes live in Maven's realm
- Handler[] oldRootLoggerHandlers = java.util.logging.Logger.getLogger("").getHandlers();
+ // activateLogging() replaces them with MavenJulHandler, whose classes live in Maven's realm
Review Comment:
No, we should not. Unconditionally replacing JUL root handlers tramples on the host's logging setup in embedded scenarios (IDE plugins, build servers with custom `LogManager`). The guard should be:
```java
if (LogManager.getLogManager().getClass() == LogManager.class) {
// default LogManager — safe to install MavenJulHandler and set root level
} else {
// custom LogManager (Log4j2-JUL bridge, container, etc.) — skip JUL setup
// and skip ProjectBuildLogAppender's JUL capture path too
}
```
This matches `SLF4JBridgeHandler`'s own defense. I'll add this guard.
##########
impl/maven-core/src/main/java/org/apache/maven/internal/build/DefaultLogEvent.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.internal.build;
+
+import java.time.Instant;
+
+import org.apache.maven.api.build.report.LogEvent;
+import org.apache.maven.api.build.report.LogLevel;
+
+/**
+ * Immutable implementation of {@link LogEvent}.
+ * <p>
+ * Public to allow construction from other packages within the Maven
+ * implementation (e.g. {@code ProjectBuildLogAppender}).
+ *
+ * @param timestamp when the event was produced
+ * @param level the severity level
+ * @param message the clean log message (without level prefix or ANSI)
+ * @param loggerName the name of the logger, or {@code null}
+ * @param stackTrace the stack trace string, or {@code null}
+ * @param formattedMessage the fully formatted console line, or {@code null}
+ * @param sourceClassName the source class name (Log API mojo FQCN or JUL source), or {@code null}
+ * @param sourceMethodName the source method name (via StackWalker or JUL), or {@code null}
+ * @param threadId the originating thread ID, or {@code -1} if unavailable
+ * @param sequenceNumber the global sequence number for ordering, or {@code -1} if unavailable
+ * @param projectId the project this event belongs to, or {@code null}
+ * @param mojoId the mojo execution that produced this event, or {@code null}
+ */
+public record DefaultLogEvent(
Review Comment:
Yes, absolutely — capture it at event creation time. Reconstructing thread name from `threadId()` after the fact is fragile: the thread may be gone, pooled thread names rotate. `Thread.currentThread().getName()` at publish time (in `ProjectBuildLogAppender` and `MavenJulHandler`) is cheap and deterministic. Note that JUL's `LogRecord.getThreadID()` does not provide the name, so we'd read it from `Thread.currentThread().getName()` at the point `MavenJulHandler.publish()` is called.
I'll add `threadName()` as a field on `DefaultLogEvent` and populate it in both capture paths.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #12694:
URL: https://github.com/apache/maven/pull/12694#issuecomment-5752282206
Fixed in cbc1d608db: restored master's lifecycle plugin versions in `impl/maven-core/pom.xml` (all 13 properties bumped to match master — clean/3.5.0, compiler/3.16.0, deploy/3.2.0, ear/3.4.0, ejb/3.3.0, install/3.2.0, jar/3.5.1, plugin-plugin/3.16.0, rar/3.1.0, resources/3.5.0, site/3.22.0, surefire/3.6.0, war/3.5.1). The rebase had inadvertently kept the older versions from the original branch point. The `plugin-versions.properties` and `PluginVersions.java` files already use `lifecycle.*` correctly — only the POM version numbers needed updating.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4012367707
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +447,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
Review Comment:
Fixed in 2fc5fc86d6: quiet-mode JUL root level changed from `WARNING` to `SEVERE` (the correct JUL equivalent of SLF4J ERROR). Updated the comment accordingly.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +457,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
Review Comment:
Fixed in 2fc5fc86d6.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048599366
##########
impl/maven-core/src/main/resources/org/apache/maven/lifecycle/plugin-versions.properties:
##########
@@ -17,19 +17,19 @@
# Default lifecycle plugin versions.
# Values are substituted by Maven resource filtering at build time from
-# POM properties (lifecycle.<name>-plugin), making them visible to
+# POM properties (version.maven-<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
-lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
-lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
-lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
-lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
-lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
-lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
-lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
-lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
-lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
-lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
-lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
-lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
-lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
+version.maven-clean-plugin=${version.maven-clean-plugin}
+version.maven-compiler-plugin=${version.maven-compiler-plugin}
+version.maven-deploy-plugin=${version.maven-deploy-plugin}
+version.maven-ear-plugin=${version.maven-ear-plugin}
+version.maven-ejb-plugin=${version.maven-ejb-plugin}
+version.maven-install-plugin=${version.maven-install-plugin}
+version.maven-jar-plugin=${version.maven-jar-plugin}
+version.maven-plugin-plugin=${version.maven-plugin-plugin}
+version.maven-rar-plugin=${version.maven-rar-plugin}
+version.maven-resources-plugin=${version.maven-resources-plugin}
+version.maven-site-plugin=${version.maven-site-plugin}
+version.maven-surefire-plugin=${version.maven-surefire-plugin}
+version.maven-war-plugin=${version.maven-war-plugin}
Review Comment:
**[high] Rebase conflict: `version.*` key names don't match POM properties — CI fails on class load**
The properties file references `${version.maven-*-plugin}` placeholders, but the POM declares `<lifecycle.maven-*-plugin>` properties (e.g. `<lifecycle.maven-ejb-plugin>3.3.0</lifecycle.maven-ejb-plugin>`). Maven resource filtering substitutes `${lifecycle.maven-ejb-plugin}` but leaves `${version.maven-ejb-plugin}` as a literal string, so `PluginVersions.version()` throws:
```
ExceptionInInitializerError: plugin-versions.properties was not filtered at build time;
version.maven-ejb-plugin still contains placeholder: ${version.maven-ejb-plugin}
```
This brings down `DefaultLifecycleRegistry$CleanLifecycle` at static init time, causing 100+ test failures across `maven-core`.
The fix is to rename both the property file keys and the `PluginVersions.java` key prefix from `version.*` to `lifecycle.*`, aligning with the POM property names that master uses:
```suggestion
# POM properties (lifecycle.<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
```
Also update `PluginVersions.java` line `String key = "version." + pluginArtifactId;` → `String key = "lifecycle." + pluginArtifactId;` and the Javadoc comment in the same file.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046255944
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -87,8 +87,6 @@ default void trace(Throwable error) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
*/
default void trace(Supplier<String> content) {}
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -97,9 +95,6 @@ default void trace(Supplier<String> content) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
- * @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +457,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
+ } else if (context.invokerRequest.effectiveVerbose()) {
+ julRootLevel = java.util.logging.Level.ALL;
+ } else {
+ julRootLevel = java.util.logging.Level.INFO;
+ }
+ java.util.logging.LogManager.getLogManager().getLogger("").setLevel(julRootLevel);
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
##########
impl/maven-logging/src/test/java/org/apache/maven/slf4j/MavenJulHandlerTest.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.slf4j;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Tests for {@link MavenJulHandler}, focused on the JUL→SLF4J level
+ * mapping and metadata lifecycle.
+ */
+class MavenJulHandlerTest {
+
+ /**
+ * Table test for JUL level → SLF4J level mapping.
+ * Verifies the mapping documented in the class Javadoc.
+ */
+ @ParameterizedTest(name = "JUL {0} -> SLF4J level {1}")
+ @CsvSource({
+ "FINEST, 0", // TRACE_INT = 0
+ "FINER, 10", // DEBUG_INT = 10
+ "FINE, 10", // DEBUG_INT = 10
+ "CONFIG, 20", // INFO_INT = 20
+ "INFO, 20", // INFO_INT = 20
+ "WARNING, 30", // WARN_INT = 30
+ "SEVERE, 40", // ERROR_INT = 40
+ })
+ void julLevelMapsToCorrectSlf4jLevel(String julLevelName, int expectedSlf4jLevel) throws Exception {
+ Level julLevel = Level.parse(julLevelName);
+ int actual = invokeJulLevelToSlf4j(julLevel);
+ assertEquals(
+ expectedSlf4jLevel, actual, "JUL " + julLevelName + " should map to SLF4J level " + expectedSlf4jLevel);
+ }
+
+ /**
+ * Verify that FINEST maps to TRACE (not DEBUG) — this is the key
+ * distinction for the TRACE/DEBUG separation.
+ */
+ @Test
+ void finestMapsToTrace() throws Exception {
+ assertEquals(
+ LocationAwareLogger.TRACE_INT,
+ invokeJulLevelToSlf4j(Level.FINEST),
+ "FINEST should map to TRACE, not DEBUG");
+ }
+
+ /**
+ * Verify that CONFIG maps to INFO (not DEBUG) — CONFIG is JUL's
+ * informational level for static configuration, not a debug level.
+ */
+ @Test
+ void configMapsToInfo() throws Exception {
+ assertEquals(LocationAwareLogger.INFO_INT, invokeJulLevelToSlf4j(Level.CONFIG), "CONFIG should map to INFO");
+ }
+
+ /**
+ * Verify that JUL metadata is null when no log event is being processed.
+ */
+ @Test
+ void julMetadataIsNullOutsidePublish() {
+ assertNull(MavenJulHandler.getJulMetadata(), "JUL metadata should be null outside a publish() call");
+ }
+
+ /**
+ * Verify that a recursive call to {@link MavenJulHandler#publish} from
+ * within a {@code publish()} call on the same thread is silently dropped
+ * instead of crashing with {@code IllegalStateException("Recursive update")}.
+ * <p>
+ * This is the reentrancy scenario that occurs when JLine's
+ * {@code StyleResolver} logs a JUL DEBUG event while
+ * {@code MavenSimpleLogger.renderLevel()} is lazily initialising ANSI
+ * colour strings during terminal construction.
+ */
+ @Test
+ void publishIsReentrantSafe() throws Exception {
+ MavenJulHandler handler = new MavenJulHandler();
+ java.util.logging.LogRecord outerRecord = new java.util.logging.LogRecord(Level.INFO, "outer");
+
+ // Install a custom SLF4J logger that fires a second JUL event
Review Comment:
Fixed in 222071d770705f15d26a4cd9a3646218e238a778.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046224223
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -97,9 +95,6 @@ default void trace(Supplier<String> content) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
- * @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
Review Comment:
**[medium] `@param content` and `@param error` tags dropped — regression from `caeeeb4`**
Same as the `trace(Supplier<String>)` overload above: both `@param` tags were added in `caeeeb4` and confirmed by the prior APPROVE. The squash dropped them. Every other supplier+throwable method (`debug`, `info`, `warn`, `error`) documents both parameters.
```suggestion
* The default implementation is a no-op for backward compatibility.
*
* @param content the message supplier
* @param error the error that caused this log
*/
default void trace(Supplier<String> content, Throwable error) {}
```
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +457,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
+ } else if (context.invokerRequest.effectiveVerbose()) {
+ julRootLevel = java.util.logging.Level.ALL;
+ } else {
+ julRootLevel = java.util.logging.Level.INFO;
+ }
+ java.util.logging.LogManager.getLogManager().getLogger("").setLevel(julRootLevel);
Review Comment:
**[low] Quiet-mode JUL root level should be `SEVERE`, not `WARNING`** (carried over — still open)
In quiet mode Maven sets SLF4J to `ERROR` level. The JUL equivalent of ERROR is `Level.SEVERE`. Using `Level.WARNING` lets JUL `WARNING`-level events pass the at-source gate and reach `MavenJulHandler`, where they are then filtered by `isLevelEnabled()`. The comment says the goal is to suppress events "at source" — but `SEVERE` is more precise: it matches the SLF4J ERROR threshold exactly.
`Level.SEVERE` closes the race-condition window for INFO/DEBUG just as effectively, while also being semantically correct for quiet mode. Update the comment from "keep JUL root at WARNING" to "keep JUL root at SEVERE" if adopted.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046222244
##########
api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java:
##########
@@ -87,8 +87,6 @@ default void trace(Throwable error) {}
* The supplier is only evaluated if trace is enabled.
* <p>
* The default implementation is a no-op for backward compatibility.
- *
- * @param content the message supplier
*/
default void trace(Supplier<String> content) {}
Review Comment:
**[medium] `@param content` tag dropped — regression from `caeeeb4`**
This `@param` tag was explicitly added in commit `caeeeb4` (confirmed in the APPROVE of `63ed04e`/`caeeeb4`). The squash-rebase dropped it. Every other supplier-based method in this interface documents its `@param content`.
```suggestion
* The default implementation is a no-op for backward compatibility.
*
* @param content the message supplier
*/
default void trace(Supplier<String> content) {}
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on PR #12694:
URL: https://github.com/apache/maven/pull/12694#issuecomment-5730916989
Fixed the Windows CI failure in `MavenITmng4387QuietLoggingTest`.
**Root cause:** In quiet mode (`-q`), the call order in `doInvoke()` is:
1. `configureLogging()` — sets SLF4J root to ERROR, but JUL handler not yet installed
2. `createTerminal()` — JLine initializes, emitting DEBUG messages via `java.util.logging` (`Available providers: exec`, `Using terminal ExternalTerminal`, `Grapheme cluster mode: not supported by terminal`)
3. `activateLogging()` — installs `MavenJulHandler` and sets JUL root to `SEVERE`
The JLine terminal-init JUL events fired between steps 1 and 3, before `MavenJulHandler` was installed to apply the SLF4J level gate, causing those `[DEBUG]` lines to leak into quiet-mode output.
**Fix:** In `configureLogging()`, when quiet mode is detected, eagerly install `MavenJulHandler` and set the JUL root level to `SEVERE` before `createTerminal()` runs. This is safe — `SEVERE` only blocks events, so it cannot trigger the `ConcurrentHashMap.computeIfAbsent` reentrancy flood that `Level.ALL` would cause during SLF4J bootstrap. `activateLogging()` still sets the JUL level (idempotently for quiet mode).
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r3879511786
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,249 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.apache.maven.api.services.MessageBuilder;
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.apache.maven.jline.MessageUtils.builder;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * When a {@link MavenSimpleLogger.LogSink LogSink} is installed (i.e. during
+ * a build), JUL events are sent directly to the sink — bypassing SLF4J
+ * entirely. The JUL metadata is stashed in a thread-local so downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * When no LogSink is installed (e.g. during early bootstrap), the handler
+ * falls back to routing through SLF4J for console output.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Returns the JUL metadata for the current log event being processed,
+ * or {@code null} if the current log event did not originate from JUL.
+ * <p>
+ * This method is intended to be called from within a
+ * {@link MavenSimpleLogger.LogSink} callback (e.g. in
+ * {@code ProjectBuildLogAppender.accept()}).
+ *
+ * @return the current JUL metadata, or {@code null}
+ */
+ public static JulMetadata getJulMetadata() {
+ return METADATA.get();
+ }
+
+ /**
+ * Installs this handler on the JUL root logger, removing any
+ * previously installed handlers. This replaces the standard
+ * {@code SLF4JBridgeHandler.install()} call.
+ */
+ public static void install() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ // Remove all existing handlers (including any SLF4JBridgeHandler)
+ for (Handler handler : rootLogger.getHandlers()) {
+ rootLogger.removeHandler(handler);
+ }
+ rootLogger.addHandler(new MavenJulHandler());
+ // Accept all levels — filtering is done by SLF4J
+ rootLogger.setLevel(Level.ALL);
+ }
+
+ /**
+ * Returns {@code true} if a {@code MavenJulHandler} is installed
+ * on the JUL root logger.
+ */
+ public static boolean isInstalled() {
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ for (Handler handler : rootLogger.getHandlers()) {
+ if (handler instanceof MavenJulHandler) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public void publish(LogRecord record) {
+ if (record == null) {
+ return;
+ }
+
+ String loggerName = record.getLoggerName();
+ org.slf4j.Logger slf4jLogger = LoggerFactory.getLogger(loggerName);
Review Comment:
Fixed — added a null guard: `if (loggerName == null) { loggerName = ""; }`. SLF4J's `LoggerFactory.getLogger("")` returns the root logger, which is safe.
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -70,15 +101,74 @@ protected String renderLevel(int level) {
}
@Override
- protected void write(StringBuilder buf, Throwable t) {
- Consumer<String> sink = logSink;
+ protected void write(int level, String loggerName, String cleanMessage, StringBuilder formattedBuf, Throwable t) {
+ LogSink sink = logSink;
if (sink != null) {
- sink.accept(buf.toString());
+ // Build the full formatted output including throwable rendering
+ String formatted = formattedBuf.toString();
if (t != null) {
- writeThrowable(t, sink);
+ StringBuilder full = new StringBuilder(formatted);
+ full.append(System.lineSeparator());
+ appendFormattedThrowable(full, t, "");
Review Comment:
Fixed — unified throwable rendering: the `write()` method now calls the existing `writeThrowable()` method instead of hand-rolling its own `appendFormattedThrowable()`/`appendStackTrace()`. Removed the duplicate methods entirely — single rendering path now.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4012596864
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -447,12 +447,31 @@ protected Consumer<String> doDetermineWriter(C context) {
}
protected void activateLogging(C context) throws Exception {
- if (!SLF4JBridgeHandler.isInstalled()) {
- SLF4JBridgeHandler.removeHandlersForRootLogger();
- SLF4JBridgeHandler.install();
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
}
context.slf4jConfiguration.activate();
+
+ // Now that SLF4J is fully initialized, set the JUL root logger level
+ // to match the effective log level. This must happen AFTER install()
+ // + activate() to avoid flooding JUL events during SLF4J bootstrap
+ // (ConcurrentHashMap.computeIfAbsent reentrancy).
+ // In quiet mode keep the JUL root at WARNING so that INFO/DEBUG JUL
+ // events are suppressed at source — relying solely on the SLF4J-level
+ // check in MavenJulHandler.isLevelEnabled() is racy: newly created
+ // SLF4J loggers may briefly see the default INFO level before
+ // quiet-mode propagation completes, leaking output that
+ // MavenITmng4387QuietLoggingTest detects as a flaky failure.
+ java.util.logging.Level julRootLevel;
+ if (context.options().quiet().orElse(false)) {
+ julRootLevel = java.util.logging.Level.WARNING;
+ } else if (context.invokerRequest.effectiveVerbose()) {
+ julRootLevel = java.util.logging.Level.ALL;
+ } else {
+ julRootLevel = java.util.logging.Level.INFO;
+ }
+ java.util.logging.LogManager.getLogManager().getLogger("").setLevel(julRootLevel);
Review Comment:
Fixed in 9cc0d82488. The comment on line 460 now reads `keep the JUL root at SEVERE so that WARNING/INFO/DEBUG` — updated together with the `Level.WARNING → Level.SEVERE` 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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4046225880
##########
impl/maven-logging/src/test/java/org/apache/maven/slf4j/MavenJulHandlerTest.java:
##########
@@ -0,0 +1,151 @@
+/*
+ * 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.slf4j;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.slf4j.spi.LocationAwareLogger;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * Tests for {@link MavenJulHandler}, focused on the JUL→SLF4J level
+ * mapping and metadata lifecycle.
+ */
+class MavenJulHandlerTest {
+
+ /**
+ * Table test for JUL level → SLF4J level mapping.
+ * Verifies the mapping documented in the class Javadoc.
+ */
+ @ParameterizedTest(name = "JUL {0} -> SLF4J level {1}")
+ @CsvSource({
+ "FINEST, 0", // TRACE_INT = 0
+ "FINER, 10", // DEBUG_INT = 10
+ "FINE, 10", // DEBUG_INT = 10
+ "CONFIG, 20", // INFO_INT = 20
+ "INFO, 20", // INFO_INT = 20
+ "WARNING, 30", // WARN_INT = 30
+ "SEVERE, 40", // ERROR_INT = 40
+ })
+ void julLevelMapsToCorrectSlf4jLevel(String julLevelName, int expectedSlf4jLevel) throws Exception {
+ Level julLevel = Level.parse(julLevelName);
+ int actual = invokeJulLevelToSlf4j(julLevel);
+ assertEquals(
+ expectedSlf4jLevel, actual, "JUL " + julLevelName + " should map to SLF4J level " + expectedSlf4jLevel);
+ }
+
+ /**
+ * Verify that FINEST maps to TRACE (not DEBUG) — this is the key
+ * distinction for the TRACE/DEBUG separation.
+ */
+ @Test
+ void finestMapsToTrace() throws Exception {
+ assertEquals(
+ LocationAwareLogger.TRACE_INT,
+ invokeJulLevelToSlf4j(Level.FINEST),
+ "FINEST should map to TRACE, not DEBUG");
+ }
+
+ /**
+ * Verify that CONFIG maps to INFO (not DEBUG) — CONFIG is JUL's
+ * informational level for static configuration, not a debug level.
+ */
+ @Test
+ void configMapsToInfo() throws Exception {
+ assertEquals(LocationAwareLogger.INFO_INT, invokeJulLevelToSlf4j(Level.CONFIG), "CONFIG should map to INFO");
+ }
+
+ /**
+ * Verify that JUL metadata is null when no log event is being processed.
+ */
+ @Test
+ void julMetadataIsNullOutsidePublish() {
+ assertNull(MavenJulHandler.getJulMetadata(), "JUL metadata should be null outside a publish() call");
+ }
+
+ /**
+ * Verify that a recursive call to {@link MavenJulHandler#publish} from
+ * within a {@code publish()} call on the same thread is silently dropped
+ * instead of crashing with {@code IllegalStateException("Recursive update")}.
+ * <p>
+ * This is the reentrancy scenario that occurs when JLine's
+ * {@code StyleResolver} logs a JUL DEBUG event while
+ * {@code MavenSimpleLogger.renderLevel()} is lazily initialising ANSI
+ * colour strings during terminal construction.
+ */
+ @Test
+ void publishIsReentrantSafe() throws Exception {
+ MavenJulHandler handler = new MavenJulHandler();
+ java.util.logging.LogRecord outerRecord = new java.util.logging.LogRecord(Level.INFO, "outer");
+
+ // Install a custom SLF4J logger that fires a second JUL event
Review Comment:
**[low] Test comment describes a scenario that the test does not implement** (nit — not blocking)
The comment says "Install a custom SLF4J logger that fires a second JUL event" but the test never installs such a logger — it sets `IN_PUBLISH=true` externally and calls `publish()` directly to verify the guard. The assertion is correct but the comment will mislead future readers.
Suggest replacing with:
```java
// Simulate re-entrance: set IN_PUBLISH=true before calling publish().
// The reentrancy guard should short-circuit without throwing or logging.
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4047369011
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @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}
+ * @since 4.1.0
Review Comment:
Fixed in 54177fcc4b. Dropped the redundant `@since 4.1.0` from `projectId()` — the interface itself is already tagged `@since 4.1.0`.
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,191 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the formatted 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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
+
+ // ---- 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.
+ * <p>
+ * Populated for both Log API and JUL events. Returns {@code -1}
+ * if the thread ID is not available (i.e. for direct SLF4J events).
+ *
+ * @return the thread ID, or {@code -1} if unavailable
+ */
+ default long threadId() {
+ return -1;
+ }
+
+ /**
+ * A monotonically increasing sequence number for total ordering of
+ * log events, useful when multiple events share the same timestamp.
+ * <p>
+ * Assigned by the logging pipeline when the event is captured,
+ * providing a global ordering across all event sources (Log API,
+ * JUL, and direct SLF4J).
+ *
+ * @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}
+ * @since 4.1.0
+ */
+ @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}
+ * @since 4.1.0
Review Comment:
Fixed in 54177fcc4b. Same — dropped the redundant `@since 4.1.0` from `mojoId()`.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4048669361
##########
impl/maven-core/src/main/resources/org/apache/maven/lifecycle/plugin-versions.properties:
##########
@@ -17,19 +17,19 @@
# Default lifecycle plugin versions.
# Values are substituted by Maven resource filtering at build time from
-# POM properties (lifecycle.<name>-plugin), making them visible to
+# POM properties (version.maven-<name>-plugin), making them visible to
# dependency-update bots such as Dependabot and Renovate.
-lifecycle.maven-clean-plugin=${lifecycle.maven-clean-plugin}
-lifecycle.maven-compiler-plugin=${lifecycle.maven-compiler-plugin}
-lifecycle.maven-deploy-plugin=${lifecycle.maven-deploy-plugin}
-lifecycle.maven-ear-plugin=${lifecycle.maven-ear-plugin}
-lifecycle.maven-ejb-plugin=${lifecycle.maven-ejb-plugin}
-lifecycle.maven-install-plugin=${lifecycle.maven-install-plugin}
-lifecycle.maven-jar-plugin=${lifecycle.maven-jar-plugin}
-lifecycle.maven-plugin-plugin=${lifecycle.maven-plugin-plugin}
-lifecycle.maven-rar-plugin=${lifecycle.maven-rar-plugin}
-lifecycle.maven-resources-plugin=${lifecycle.maven-resources-plugin}
-lifecycle.maven-site-plugin=${lifecycle.maven-site-plugin}
-lifecycle.maven-surefire-plugin=${lifecycle.maven-surefire-plugin}
-lifecycle.maven-war-plugin=${lifecycle.maven-war-plugin}
+version.maven-clean-plugin=${version.maven-clean-plugin}
+version.maven-compiler-plugin=${version.maven-compiler-plugin}
+version.maven-deploy-plugin=${version.maven-deploy-plugin}
+version.maven-ear-plugin=${version.maven-ear-plugin}
+version.maven-ejb-plugin=${version.maven-ejb-plugin}
Review Comment:
**[high] Property key mismatch — filtering placeholder will never be substituted, breaking 100+ lifecycle tests**
This file now uses `version.maven-*-plugin` placeholders (e.g. `${version.maven-ejb-plugin}` on this line), but `impl/maven-core/pom.xml` still defines the properties as `<lifecycle.maven-ejb-plugin>3.3.0</lifecycle.maven-ejb-plugin>` (new file line 43). Maven resource filtering can only substitute a placeholder if the property name in the POM **exactly** matches the `${...}` expression in the template.
Because there is no `<version.maven-ejb-plugin>` property in the POM, the placeholder survives filtering as a literal string. `PluginVersions.java` then reads `version.maven-ejb-plugin=\${version.maven-ejb-plugin}` and throws:
```
ExceptionInInitializerError: plugin-versions.properties was not filtered at build time;
version.maven-ejb-plugin still contains placeholder: ${version.maven-ejb-plugin}
```
CI confirms: every test that touches `PluginVersions` fails with this error (LifecycleExecutorTest, BuildPlanCreatorTest, etc.).
**Root cause:** The squash-rebase onto master picked up commit `ab8947053d` (`chore: add versions:update-properties workflow`) which renamed the POM properties from `version.*` → `lifecycle.*`. This PR simultaneously reverts those POM names back to `lifecycle.*` (bumped versions from master) but also changes `plugin-versions.properties` and `PluginVersions.java` to use `version.*` — leaving the three files inconsistent.
**Fix:** In `impl/maven-core/pom.xml`, rename all 13 `<lifecycle.maven-*-plugin>` properties to `<version.maven-*-plugin>` (keeping the updated version numbers from master):
```suggestion
version.maven-ejb-plugin=${version.maven-ejb-plugin}
```
##########
impl/maven-core/pom.xml:
##########
@@ -36,19 +36,19 @@ under the License.
Maintained here so that dependency-update bots (Dependabot, Renovate)
can propose version bumps automatically. Values are filtered into
plugin-versions.properties at build time and loaded at runtime. -->
- <lifecycle.maven-clean-plugin>3.4.0</lifecycle.maven-clean-plugin>
- <lifecycle.maven-compiler-plugin>3.13.0</lifecycle.maven-compiler-plugin>
- <lifecycle.maven-deploy-plugin>3.1.3</lifecycle.maven-deploy-plugin>
- <lifecycle.maven-ear-plugin>3.3.0</lifecycle.maven-ear-plugin>
- <lifecycle.maven-ejb-plugin>3.2.1</lifecycle.maven-ejb-plugin>
- <lifecycle.maven-install-plugin>3.1.3</lifecycle.maven-install-plugin>
- <lifecycle.maven-jar-plugin>3.4.2</lifecycle.maven-jar-plugin>
- <lifecycle.maven-plugin-plugin>3.15.1</lifecycle.maven-plugin-plugin>
- <lifecycle.maven-rar-plugin>3.0.0</lifecycle.maven-rar-plugin>
- <lifecycle.maven-resources-plugin>3.3.1</lifecycle.maven-resources-plugin>
- <lifecycle.maven-site-plugin>3.21.0</lifecycle.maven-site-plugin>
- <lifecycle.maven-surefire-plugin>3.5.2</lifecycle.maven-surefire-plugin>
- <lifecycle.maven-war-plugin>3.4.0</lifecycle.maven-war-plugin>
+ <lifecycle.maven-clean-plugin>3.5.0</lifecycle.maven-clean-plugin>
+ <lifecycle.maven-compiler-plugin>3.16.0</lifecycle.maven-compiler-plugin>
+ <lifecycle.maven-deploy-plugin>3.2.0</lifecycle.maven-deploy-plugin>
+ <lifecycle.maven-ear-plugin>3.4.0</lifecycle.maven-ear-plugin>
+ <lifecycle.maven-ejb-plugin>3.3.0</lifecycle.maven-ejb-plugin>
+ <lifecycle.maven-install-plugin>3.2.0</lifecycle.maven-install-plugin>
+ <lifecycle.maven-jar-plugin>3.5.1</lifecycle.maven-jar-plugin>
+ <lifecycle.maven-plugin-plugin>3.16.0</lifecycle.maven-plugin-plugin>
+ <lifecycle.maven-rar-plugin>3.1.0</lifecycle.maven-rar-plugin>
+ <lifecycle.maven-resources-plugin>3.5.0</lifecycle.maven-resources-plugin>
+ <lifecycle.maven-site-plugin>3.22.0</lifecycle.maven-site-plugin>
+ <lifecycle.maven-surefire-plugin>3.6.0</lifecycle.maven-surefire-plugin>
+ <lifecycle.maven-war-plugin>3.5.1</lifecycle.maven-war-plugin>
Review Comment:
**[high] POM property names must match `plugin-versions.properties` placeholders**
This block defines `<lifecycle.maven-*-plugin>` properties, but `plugin-versions.properties` (changed in this same PR) uses `${version.maven-*-plugin}` placeholders. Maven resource filtering looks up properties by exact name — these never match, so all 13 placeholders survive unresolved.
Rename all 13 properties here from `lifecycle.*` to `version.*` to align with the new `plugin-versions.properties` and `PluginVersions.java`:
```suggestion
<version.maven-clean-plugin>3.5.0</version.maven-clean-plugin>
<version.maven-compiler-plugin>3.16.0</version.maven-compiler-plugin>
<version.maven-deploy-plugin>3.2.0</version.maven-deploy-plugin>
<version.maven-ear-plugin>3.4.0</version.maven-ear-plugin>
<version.maven-ejb-plugin>3.3.0</version.maven-ejb-plugin>
<version.maven-install-plugin>3.2.0</version.maven-install-plugin>
<version.maven-jar-plugin>3.5.1</version.maven-jar-plugin>
<version.maven-plugin-plugin>3.16.0</version.maven-plugin-plugin>
<version.maven-rar-plugin>3.1.0</version.maven-rar-plugin>
<version.maven-resources-plugin>3.5.0</version.maven-resources-plugin>
<version.maven-site-plugin>3.22.0</version.maven-site-plugin>
<version.maven-surefire-plugin>3.6.0</version.maven-surefire-plugin>
<version.maven-war-plugin>3.5.1</version.maven-war-plugin>
```
Also update the `pluginManagement` comment on line 284 (currently says `lifecycle.maven-*-plugin`) to say `version.maven-*-plugin` for consistency.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4058009289
##########
impl/maven-core/src/main/java/org/apache/maven/internal/transformation/impl/PomInlinerTransformer.java:
##########
@@ -140,28 +125,12 @@ public void injectTransformedArtifacts(RepositorySystemSession session, MavenPro
String newVersion;
if (version != null) {
HashSet<String> usedProperties = new HashSet<>();
- Map<String, String> pomProperties = pomProperties(session);
newVersion = interpolator.interpolate(version.trim(), property -> {
- if (session.getConfigProperties().containsKey(property)) {
- usedProperties.add(property);
- return (String) session.getConfigProperties().get(property);
- }
- // CI-friendly version properties (revision, sha1, changelist) may be
- // defined in the POM's <properties> section rather than passed via -D.
- // In that case, fall back to the project's effective properties so the
- // installed/deployed POM gets the literal version inlined for consumers.
- String projectValue = project.getProperties().getProperty(property);
- if (projectValue != null) {
- usedProperties.add(property);
- // Remember this value for replacePom(), which does not have a project ref.
- // Key by groupId:artifactId:property to avoid cross-project collision
- // in a reactor build where multiple modules may define the same property.
- pomProperties.put(
- project.getGroupId() + ":" + project.getArtifactId() + ":" + property,
- projectValue);
- return projectValue;
+ if (!session.getConfigProperties().containsKey(property)) {
+ throw new IllegalArgumentException("Cannot inline property " + property);
Review Comment:
Fixed in 628c65fa70: restored `pomProperties` fallback in `PomInlinerTransformer` (matching master's GH-13192 fix), and also restored the `MavenITgh13192PomInlinerCiFriendlyPropertyTest` IT test + resources that were dropped in the squash-rebase.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategy.java:
##########
@@ -836,11 +847,16 @@ private PluginAnalysisResults analyzePluginsUsingEffectiveModels(
Path originalPomPath = entry.getKey();
try {
+ // Find the corresponding temp POM path
+ Path commonRoot = findCommonRoot(pomMap.keySet());
Review Comment:
Fixed in 628c65fa70: `findCommonRoot(pomMap.keySet())` is now hoisted out of the loop with a comment explaining why.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4057996020
##########
impl/maven-core/src/main/java/org/apache/maven/internal/transformation/impl/PomInlinerTransformer.java:
##########
@@ -140,28 +125,12 @@ public void injectTransformedArtifacts(RepositorySystemSession session, MavenPro
String newVersion;
if (version != null) {
HashSet<String> usedProperties = new HashSet<>();
- Map<String, String> pomProperties = pomProperties(session);
newVersion = interpolator.interpolate(version.trim(), property -> {
- if (session.getConfigProperties().containsKey(property)) {
- usedProperties.add(property);
- return (String) session.getConfigProperties().get(property);
- }
- // CI-friendly version properties (revision, sha1, changelist) may be
- // defined in the POM's <properties> section rather than passed via -D.
- // In that case, fall back to the project's effective properties so the
- // installed/deployed POM gets the literal version inlined for consumers.
- String projectValue = project.getProperties().getProperty(property);
- if (projectValue != null) {
- usedProperties.add(property);
- // Remember this value for replacePom(), which does not have a project ref.
- // Key by groupId:artifactId:property to avoid cross-project collision
- // in a reactor build where multiple modules may define the same property.
- pomProperties.put(
- project.getGroupId() + ":" + project.getArtifactId() + ":" + property,
- projectValue);
- return projectValue;
+ if (!session.getConfigProperties().containsKey(property)) {
+ throw new IllegalArgumentException("Cannot inline property " + property);
Review Comment:
**[high] CI-friendly version regression — reverts the GH-13192 fix**
This squash drops the `pomProperties` fallback from `injectTransformedArtifacts()` and the corresponding fallback in `replacePom()`. The deleted `MavenITgh13192PomInlinerCiFriendlyPropertyTest` was specifically testing this path: projects that define `${revision}` (or `${sha1}`, `${changelist}`) in `<properties>` rather than via `-D` on the command line will now fail with `IllegalArgumentException: Cannot inline property revision` in legacy mode.
The fix (`47e80246` on master) was:
1. Fall back to `project.getProperties().getProperty(property)` when the property is not in `session.getConfigProperties()`
2. Cache the resolved value in `pomProperties` (keyed by `groupId:artifactId:property`) for use in `replacePom()`, which has no `project` reference
Both the fix and the IT need to be restored. The fix is currently on master at `47e80246` and should not have been squashed away.
If this was intentional (e.g. the feature is being moved to a separate PR), the PR description should say so explicitly and the IT should not be deleted here.
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/mvnup/goals/PluginUpgradeStrategy.java:
##########
@@ -836,11 +847,16 @@ private PluginAnalysisResults analyzePluginsUsingEffectiveModels(
Path originalPomPath = entry.getKey();
try {
+ // Find the corresponding temp POM path
+ Path commonRoot = findCommonRoot(pomMap.keySet());
Review Comment:
**[medium] `findCommonRoot` called per-module iteration — O(n²) on the reactor**
`findCommonRoot(pomMap.keySet())` is called once per module inside the `for (Map.Entry<Path, Document> entry : pomMap.entrySet())` loop. `findCommonRoot` iterates over all paths to compute the common ancestor, so a reactor with N modules calls it N times — each call is O(N), making the loop O(N²).
Fix: compute once before the loop and pass down (the call site in `createTempProjectStructure` already does this correctly).
```suggestion
Path commonRoot = findCommonRoot(pomMap.keySet());
for (Map.Entry<Path, Document> entry : pomMap.entrySet()) {
Path originalPomPath = entry.getKey();
try {
// Find the corresponding temp POM path
Path relativePath = commonRoot.relativize(originalPomPath);
Path tempPomPath = tempDir.resolve(relativePath);
```
(Move the `Path commonRoot = findCommonRoot(pomMap.keySet());` line above the `for` loop — it was at line 851 inside the loop body. The `relativePath` and `tempPomPath` locals stay inside the loop.)
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4079558621
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenJulHandler.java:
##########
@@ -0,0 +1,318 @@
+/*
+ * 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.slf4j;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.logging.Handler;
+import java.util.logging.Level;
+import java.util.logging.LogManager;
+import java.util.logging.LogRecord;
+import java.util.logging.Logger;
+
+import org.slf4j.LoggerFactory;
+import org.slf4j.spi.LocationAwareLogger;
+
+/**
+ * A JUL {@link Handler} that routes {@code java.util.logging} events into
+ * Maven's structured logging pipeline, preserving the rich {@link LogRecord}
+ * metadata that the standard {@code SLF4JBridgeHandler} silently drops
+ * (source class name, source method name, thread ID).
+ * <p>
+ * All JUL events are routed through SLF4J so that {@link MavenSimpleLogger}
+ * produces a consistent {@code formattedMessage} (with timestamp, logger name,
+ * and ANSI styling) regardless of the event's origin. The JUL metadata is
+ * stashed in a thread-local <em>before</em> the SLF4J call so that downstream
+ * consumers (e.g. {@code ProjectBuildLogAppender}) can read it when
+ * constructing a structured {@code LogEvent}.
+ * <p>
+ * Usage — replace the standard SLF4J bridge in {@code LookupInvoker}:
+ * <pre>
+ * MavenJulHandler.install();
+ * </pre>
+ *
+ * @since 4.1.0
+ * @see #install()
+ * @see #getJulMetadata()
+ */
+public class MavenJulHandler extends Handler {
+
+ /**
+ * JUL metadata captured from a {@link LogRecord} that would otherwise
+ * be lost when bridging to SLF4J.
+ *
+ * @param sourceClassName the source class, or {@code null}
+ * @param sourceMethodName the source method, or {@code null}
+ * @param threadId the originating thread ID
+ */
+ public record JulMetadata(String sourceClassName, String sourceMethodName, long threadId) {}
+
+ private static final ThreadLocal<JulMetadata> METADATA = new ThreadLocal<>();
+
+ /**
+ * Private SLF4J logger cache using {@link ConcurrentMap#putIfAbsent}
+ * instead of {@link ConcurrentMap#computeIfAbsent}. This avoids the
+ * {@code ConcurrentHashMap.computeIfAbsent} reentrancy bug
+ * ({@code IllegalStateException("Recursive update")}) that occurs
+ * when a JUL event fires during SLF4J logger initialization: the
+ * handler's {@code publish()} calls {@code LoggerFactory.getLogger()},
+ * which internally uses {@code computeIfAbsent}, and if that triggers
+ * another JUL event whose logger name hashes to the same bucket,
+ * {@code ConcurrentHashMap} throws. {@code putIfAbsent} is safe
+ * against reentrancy — worst case, two threads create the same
+ * logger and one is discarded.
+ */
+ private static final ConcurrentMap<String, org.slf4j.Logger> LOGGER_CACHE = new ConcurrentHashMap<>();
+
Review Comment:
Fixed in 1fe9484acf: added a note to the `LOGGER_CACHE` Javadoc documenting that the cache is intentionally unbounded, with the rationale that its effective size is bounded by the number of distinct JUL logger names in the JVM — a small set in practice.
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet-bot (via GitHub)" <gi...@apache.org>.
gnodet-bot commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4281689891
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -314,6 +316,20 @@ protected void configureLogging(C context) throws Exception {
} else if (context.options().quiet().orElse(false)) {
context.loggerLevel = Slf4jConfiguration.Level.ERROR;
context.slf4jConfiguration.setRootLoggerLevel(context.loggerLevel);
+ // Install the JUL handler early and clamp the JUL root to SEVERE
+ // so that JLine terminal-init DEBUG events (emitted via java.util.logging
+ // before activateLogging() runs) are suppressed at source.
+ // createTerminal() executes after configureLogging() but before
+ // activateLogging(), so without this guard those DEBUG lines leak
+ // into the build output even when -q is in effect, causing
+ // MavenITmng4387QuietLoggingTest to fail on Windows.
+ // Setting SEVERE here is safe: it only blocks events, so it
+ // cannot trigger the SLF4J-bootstrap reentrancy flood that
+ // Level.ALL would cause.
+ if (!MavenJulHandler.isInstalled()) {
+ MavenJulHandler.install();
+ }
+ LogManager.getLogManager().getLogger("").setLevel(Level.SEVERE);
Review Comment:
**[medium] JUL root logger level is set but never restored — leaks to host JVM in embedded scenarios**
This PR introduces two `setLevel()` calls on the JUL root logger:
- `configureLogging()` quiet mode: `getLogger("").setLevel(Level.SEVERE)` (here, line 332)
- `activateLogging()`: `getLogger("").setLevel(julRootLevel)` (line 511)
`restoreRootLoggerHandlers` (and the `invoke()` finally block) restores the old handlers but not the old level. In embedded-Maven scenarios (IDE plugin, another JVM host), the level change leaks: quiet mode leaves the root permanently at `SEVERE`, silently swallowing the host's `INFO`/`WARNING` JUL output after Maven returns.
Fix: capture the old level before invocation and restore it in the finally block.
In `invoke()`, alongside `oldRootLoggerHandlers`, add:
```java
java.util.logging.Level oldRootLoggerLevel = java.util.logging.Logger.getLogger("").getLevel();
```
Then in the `finally` block:
```java
java.util.logging.Logger.getLogger("").setLevel(oldRootLoggerLevel);
restoreRootLoggerHandlers(oldRootLoggerHandlers);
```
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "rmannibucau (via GitHub)" <gi...@apache.org>.
rmannibucau commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357173169
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @return the log message, never {@code null}
+ */
+ @Nonnull
+ String message();
Review Comment:
should it be message template? and should we get args? else i dont see why we have formatted message too
##########
impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java:
##########
@@ -125,8 +127,10 @@ public final int invoke(InvokerRequest invokerRequest) {
Properties oldProps = new Properties();
oldProps.putAll(System.getProperties());
ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
- // activateLogging() replaces them with SLF4JBridgeHandler, whose classes live in Maven's realm
- Handler[] oldRootLoggerHandlers = java.util.logging.Logger.getLogger("").getHandlers();
+ // activateLogging() replaces them with MavenJulHandler, whose classes live in Maven's realm
Review Comment:
do we want to totally ignore the JUL setup when a custom logging manager is configured?
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
+
+ /**
+ * The fully formatted log line as rendered for console output, including
+ * the level prefix, timestamp, and any ANSI styling applied by the logger.
+ * <p>
+ * This is the string that would be printed to the terminal in verbose mode.
+ * Console renderers that just need pass-through output can use this directly,
+ * while renderers that apply custom formatting (e.g. rich mode) can use the
+ * structured fields ({@link #level()}, {@link #message()}) instead.
+ * <p>
+ * May be {@code null} if the event was created outside the SLF4J pipeline
+ * (e.g. in tests or by programmatic construction).
+ *
+ * @return the formatted log line, or {@code null}
+ */
+ @Nullable
+ String formattedMessage();
Review Comment:
this should be outside the event and a particular consumer IMHO
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
Review Comment:
Throwable to keep the data for consumers and not preformat it?
##########
impl/maven-core/src/main/java/org/apache/maven/internal/build/DefaultLogEvent.java:
##########
@@ -0,0 +1,81 @@
+/*
+ * 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.internal.build;
+
+import java.time.Instant;
+
+import org.apache.maven.api.build.report.LogEvent;
+import org.apache.maven.api.build.report.LogLevel;
+
+/**
+ * Immutable implementation of {@link LogEvent}.
+ * <p>
+ * Public to allow construction from other packages within the Maven
+ * implementation (e.g. {@code ProjectBuildLogAppender}).
+ *
+ * @param timestamp when the event was produced
+ * @param level the severity level
+ * @param message the clean log message (without level prefix or ANSI)
+ * @param loggerName the name of the logger, or {@code null}
+ * @param stackTrace the stack trace string, or {@code null}
+ * @param formattedMessage the fully formatted console line, or {@code null}
+ * @param sourceClassName the source class name (Log API mojo FQCN or JUL source), or {@code null}
+ * @param sourceMethodName the source method name (via StackWalker or JUL), or {@code null}
+ * @param threadId the originating thread ID, or {@code -1} if unavailable
+ * @param sequenceNumber the global sequence number for ordering, or {@code -1} if unavailable
+ * @param projectId the project this event belongs to, or {@code null}
+ * @param mojoId the mojo execution that produced this event, or {@code null}
+ */
+public record DefaultLogEvent(
Review Comment:
open question: do we want to capture the thread name at the same time since it can be almost impossible to capture after the event (and we need to maintain a map<id, name> and re-enumerate threads lazily, not something trivial to do and redo in all consumers
##########
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenSimpleLogger.java:
##########
@@ -39,14 +39,90 @@ public class MavenSimpleLogger extends MavenBaseLogger {
private String warnRenderedLevel;
private String errorRenderedLevel;
Review Comment:
dumb question: why we dont move to jul there by default and just rework the default formatter+handler pair?
LogRecord would be neat there
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Logging foundation: structured LogEvent, JUL handler, Log API enhancements [maven]
Posted by "gnodet (via GitHub)" <gi...@apache.org>.
gnodet commented on code in PR #12694:
URL: https://github.com/apache/maven/pull/12694#discussion_r4357257256
##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/LogEvent.java:
##########
@@ -0,0 +1,189 @@
+/*
+ * 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.build.report;
+
+import java.time.Instant;
+
+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;
+
+/**
+ * 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}.
+ *
+ * @since 4.1.0
+ */
+@Experimental
+@Immutable
+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.
+ *
+ * @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 stack trace associated with this event, if an exception was logged.
+ * <p>
+ * The trace is formatted as a multi-line string and may be truncated
+ * for very deep stack traces.
+ *
+ * @return the stack trace string, or {@code null} if no exception was logged
+ */
+ @Nullable
+ String stackTrace();
Review Comment:
Agreed that keeping the raw `Throwable` is richer for consumers. The reason I went with a pre-formatted `String` was:
1. `LogEvent` is `@Immutable` and is designed to be serialisable / archivable in build reports. Keeping a live `Throwable` reference would prevent that.
2. In practice the event is captured at log time and may outlive the exception (e.g. stored in the report, exported to JSON). A pre-formatted string is always safe.
3. Different SLF4J backends may not route `Throwable` reliably — JUL's `LogRecord` does carry it via `getThrown()`, but the SLF4J normalization path in `MavenBaseLogger` doesn't always have it.
That said, I see your point: if a consumer wants to do something smarter with the exception (e.g. filter by exception type, extract the message without the stack, or format it in a structured error report), a `String` is opaque.
Possible compromise: keep `stackTrace()` as `String` (always available, serialisation-safe) and add a default-null `Throwable throwable()` for the cases where the original exception is available. Consumers that just need the formatted trace use `stackTrace()`; consumers that need the live object use `throwable()`. WDYT?
--
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: issues-unsubscribe@maven.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org