This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git
The following commit(s) were added to refs/heads/master by this push:
new 606f7df405 fix: wait for terminal installation before caching logging
output (compat) (#13860)
606f7df405 is described below
commit 606f7df4056c7bc05de7bcc0de2cf9f3b19b3406
Author: Guillaume Nodet <[email protected]>
AuthorDate: Mon Nov 9 15:16:07 2026 +0100
fix: wait for terminal installation before caching logging output (compat)
(#13860)
* fix: wait for terminal installation before caching logging output (compat)
Port of #13799 (maven-3.10.x) to master, compat layer only.
- Add MessageUtils.awaitTerminalInitialization() to impl/maven-jline
(same pattern as 3.10.x — calls FastTerminal.getTerminal() to block
until async terminal init completes)
- Add awaitTerminalInitialization() in the LOG_FILE branch of
MavenCli.logging() before System.setOut/setErr, to prevent FastTerminal's
background thread from overwriting the -l file redirection (#12188)
- Add awaitTerminalInitialization() in the else branch before
slf4jConfiguration.activate(), except when color is explicitly forced
(always/yes/force), to prevent the logger from caching the wrong stream
- Add Javadoc on awaitTerminalInitialization() explaining when and why to
call it
See also: apache/maven#13793 (issue), apache/maven#13799 (3.10.x fix)
* fix: remove dead code in MavenCliLoggingTest tearDown
restoreProperty() was called then immediately overwritten by
clearProperty() for the same keys, making the restore a no-op.
Remove the now-unused savedLogFile/savedCacheOutputStream fields,
their setUp assignments, and the restoreProperty helper.
tearDown now simply clears both properties before activateSlf4j().
* fix: exclude logback from surefire classpath and close log file on Windows
- Exclude logback-classic from the surefire test classpath in
maven-embedder so MavenLoggerFactory is the sole SLF4J provider.
On macOS aarch64, ServiceLoader picks Logback when both
maven-logging and logback-classic are on the test classpath;
LogbackConfiguration.activate() is then a no-op and the stream
assertions in MavenCliLoggingTest fail (expected: true was: false).
- In logFileBranchAwaitsTerminalBeforeRedirect, close the PrintStream
wrapping maven.log in the finally block before restoring System.out.
On Windows, an open FileOutputStream prevents @TempDir from
deleting the temp directory, causing a JUnitException at teardown.
* fix: clarify teardown comment ordering in MavenCliLoggingTest
* fix: implement getRealm() in MojoExecutionFilter plugin adapter
* fix: scope logback-classic as provided to exclude it from test classpath
The surefire classpathDependencyExcludes approach was insufficient on
macOS aarch64 CI. Changing logback-classic to provided scope is more
reliable: compile-time visibility is preserved for LogbackConfiguration,
but the JAR is absent from the test forked JVM, ensuring MavenLoggerFactory
is the sole SLF4J provider and stream assertions in MavenCliLoggingTest
pass on all platforms.
* fix: spotless - move <optional> after <scope> in logback-classic
dependency
* fix: use surefire classpathDependencyExcludes instead of provided scope
for logback
Revert from provided scope back to optional (compile) scope and add explicit
surefire classpathDependencyExcludes. The provided scope does not exclude
logback-classic from Surefire's forked test JVM classpath, so macOS aarch64
CI still picks Logback as the SLF4J provider, causing MavenCliLoggingTest
to fail with LogbackConfiguration.activate() no-op and stream assertions
returning false.
Using classpathDependencyExcludes is the correct approach: the dep remains
optional (compile-only, not transitive) and Surefire explicitly removes it
from the test classpath.
* fix: reset defaultLogLevel and logFile in SimpleLoggerConfiguration.init()
init() was not resetting defaultLogLevel and logFile to their defaults
before re-reading properties. When another test (e.g.
calculateTransferListener)
called cli.logging() with --quiet, it set maven.logger.defaultLogLevel=error
via setRootLoggerLevel(). On a subsequent init() with that property cleared,
the stale ERROR value persisted, suppressing WARN-level output and causing
MavenCliLoggingTest assertions to fail.
Also harden MavenCliLoggingTest to save/restore all logger system properties
(both maven.logger.* and org.slf4j.simpleLogger.* prefixes) and clear them
in setUp() to prevent cross-test contamination.
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
---
compat/maven-embedder/pom.xml | 17 +
.../main/java/org/apache/maven/cli/MavenCli.java | 19 +-
.../org/apache/maven/cli/MavenCliLoggingTest.java | 434 +++++++++++++++++++++
.../java/org/apache/maven/jline/MessageUtils.java | 14 +
.../maven/slf4j/SimpleLoggerConfiguration.java | 2 +
5 files changed, 484 insertions(+), 2 deletions(-)
diff --git a/compat/maven-embedder/pom.xml b/compat/maven-embedder/pom.xml
index 6974277c2b..e41c0e26f9 100644
--- a/compat/maven-embedder/pom.xml
+++ b/compat/maven-embedder/pom.xml
@@ -174,6 +174,10 @@ under the License.
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
+ <!-- compile-only (optional) for LogbackConfiguration; excluded from the
surefire
+ test classpath via classpathDependencyExcludes so
MavenLoggerFactory is the
+ sole SLF4J provider in tests (macOS aarch64 CI picks Logback when
both
+ providers are present, breaking stream assertions) -->
<optional>true</optional>
</dependency>
<dependency>
@@ -232,6 +236,19 @@ under the License.
<groupId>org.eclipse.sisu</groupId>
<artifactId>sisu-maven-plugin</artifactId>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <!-- Exclude logback-classic from the test classpath so
MavenLoggerFactory is
+ the sole SLF4J provider. Without this, ServiceLoader may pick
Logback on
+ some platforms (macOS aarch64), causing MavenCliLoggingTest to
fail because
+ LogbackConfiguration.activate() is a no-op and stream
assertions break. -->
+ <classpathDependencyExcludes>
+
<classpathDependencyExclude>ch.qos.logback:logback-classic</classpathDependencyExclude>
+ </classpathDependencyExcludes>
+ </configuration>
+ </plugin>
</plugins>
</build>
</project>
diff --git
a/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
b/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
index 4f3b641282..573f3d3806 100644
--- a/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
+++ b/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
@@ -605,6 +605,11 @@ void logging(CliRequest cliRequest) throws ExitException {
File logFile = new
File(commandLine.getOptionValue(CLIManager.LOG_FILE));
logFile = ResolveFile.resolveFile(logFile,
cliRequest.workingDirectory);
+ // make sure the terminal has finished installing before we grab
the streams, otherwise it
+ // could later overwrite our redirection and logs would leak back
to the console
+ // (see https://github.com/apache/maven/issues/12188)
+ MessageUtils.awaitTerminalInitialization();
+
// redirect stdout and stderr to file
try {
PrintStream ps = new PrintStream(new
FileOutputStream(logFile));
@@ -615,9 +620,19 @@ void logging(CliRequest cliRequest) throws ExitException {
// Ignore
//
}
- }
- slf4jConfiguration.activate();
+ // Logging caches System.out; with -l the wait above already ran,
so activate now.
+ slf4jConfiguration.activate();
+ } else {
+ // Logging caches System.out, so wait for terminal installation to
complete before
+ // activating, except when color is explicitly forced. With forced
color the user expects
+ // raw ANSI to flow through the original stdout; waiting causes
AnsiConsole to wrap that
+ // stream before the logger caches it, which may strip the escape
codes.
+ if (!"always".equals(styleColor) && !"yes".equals(styleColor) &&
!"force".equals(styleColor)) {
+ MessageUtils.awaitTerminalInitialization();
+ }
+ slf4jConfiguration.activate();
+ }
plexusLoggerManager = new Slf4jLoggerManager();
slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
diff --git
a/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
b/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
new file mode 100644
index 0000000000..5d050352d2
--- /dev/null
+++
b/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
@@ -0,0 +1,434 @@
+/*
+ * 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.cli;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.lang.reflect.Field;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.maven.api.Constants;
+import org.apache.maven.cling.logging.Slf4jConfiguration;
+import org.apache.maven.cling.logging.Slf4jConfigurationFactory;
+import org.apache.maven.jline.FastTerminal;
+import org.apache.maven.jline.MessageUtils;
+import org.apache.maven.slf4j.MavenBaseLogger;
+import org.jline.terminal.Terminal;
+import org.jline.terminal.spi.TerminalExt;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.api.parallel.Isolated;
+import org.slf4j.LoggerFactory;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+
+@Isolated("Changes JVM-wide streams, system properties, terminal state, and
logging configuration")
+class MavenCliLoggingTest {
+
+ private static final String[] SAVED_PROPERTIES = {
+ MavenBaseLogger.LEGACY_PREFIX + "logFile",
+ MavenBaseLogger.LEGACY_PREFIX + "cacheOutputStream",
+ MavenBaseLogger.LEGACY_PREFIX + "defaultLogLevel",
+ Constants.MAVEN_LOGGER_LOG_FILE,
+ Constants.MAVEN_LOGGER_CACHE_OUTPUT_STREAM,
+ Constants.MAVEN_LOGGER_DEFAULT_LOG_LEVEL,
+ };
+
+ private PrintStream savedOut;
+ private Terminal savedTerminal;
+ private boolean savedColor;
+ private final String[] savedPropertyValues = new
String[SAVED_PROPERTIES.length];
+
+ @BeforeEach
+ void setUp() throws Exception {
+ savedOut = System.out;
+ savedTerminal = getTerminalField();
+ savedColor = getColorEnabled();
+ // Null out the terminal so leftover FastTerminal threads from other
tests cannot
+ // race with this test's stream setup via their consumer callbacks.
+ injectTerminal(null);
+ for (int i = 0; i < SAVED_PROPERTIES.length; i++) {
+ savedPropertyValues[i] = System.getProperty(SAVED_PROPERTIES[i]);
+ }
+ // Clear all logger properties and re-initialize the config so
previous tests
+ // (e.g. MavenCliTest#calculateTransferListener setting
maven.logger.defaultLogLevel=error
+ // via --quiet) cannot poison this test's config.
+ for (String prop : SAVED_PROPERTIES) {
+ System.clearProperty(prop);
+ }
+ activateSlf4j();
+ }
+
+ @AfterEach
+ void tearDown() throws Exception {
+ System.setOut(savedOut);
+ injectTerminal(savedTerminal);
+ setColorEnabled(savedColor);
+ for (int i = 0; i < SAVED_PROPERTIES.length; i++) {
+ restoreProperty(SAVED_PROPERTIES[i], savedPropertyValues[i]);
+ }
+ activateSlf4j();
+ }
+
+ /**
+ * When color is explicitly forced ({@code -Dstyle.color=always}), {@code
logging()} must NOT
+ * call {@code awaitTerminalInitialization()} before activating the
logging configuration.
+ * The logger must therefore cache the stream that was active at
activation time (the "early"
+ * stream), not the stream installed by the terminal consumer afterwards.
+ * <p>
+ * On master, {@code MavenSimpleLogger.configure()} renders ANSI-coloured
level labels via
+ * {@code JLineMessageBuilderFactory}, which calls {@code
terminal.getType()} and therefore
+ * always awaits terminal initialisation inside {@code activate()}. The
key behavioral
+ * difference being tested is that with {@code color=always}, {@code
config.init()} captures
+ * {@code System.out} <em>before</em> the terminal consumer runs (because
+ * {@code awaitTerminalInitialization()} is skipped before {@code
activate()}).
+ * <p>
+ * This test uses a held-back {@link FastTerminal} instead of a {@code
DumbTerminal}. The
+ * terminal build blocks until the test releases it. Since {@code
logging()} with
+ * {@code color=always} does not call {@code
awaitTerminalInitialization()} before
+ * {@code activate()}, the logger caches {@code earlyStream} in {@code
config.init()}, then
+ * blocks inside {@code configure()} waiting for the terminal. When the
test releases the
+ * terminal, the consumer swaps {@code System.out} to {@code
terminalStream}, but the logger
+ * has already cached {@code earlyStream}.
+ */
+ @Test
+ void withColorForcedLoggerCachesEarlyStream() throws Exception {
+ CountDownLatch buildingTerminal = new CountDownLatch(1);
+ CountDownLatch releaseTerminal = new CountDownLatch(1);
+ ByteArrayOutputStream earlyOutput = new ByteArrayOutputStream();
+ ByteArrayOutputStream terminalOutput = new ByteArrayOutputStream();
+ Thread loggingThread = null;
+ try (PrintStream earlyStream = new PrintStream(earlyOutput, true,
UTF_8.name());
+ PrintStream terminalStream = new PrintStream(terminalOutput,
true, UTF_8.name())) {
+ System.setProperty(MavenBaseLogger.LEGACY_PREFIX +
"cacheOutputStream", "true");
+ System.setProperty(MavenBaseLogger.LEGACY_PREFIX + "logFile",
"System.out");
+ System.setOut(earlyStream);
+ activateSlf4j();
+
+ FastTerminal terminal = new FastTerminal(
+ () -> {
+ buildingTerminal.countDown();
+ if (!releaseTerminal.await(10, SECONDS)) {
+ throw new IllegalStateException("Terminal
installation was not released");
+ }
+ return mock(TerminalExt.class, RETURNS_DEEP_STUBS);
+ },
+ installed -> System.setOut(terminalStream));
+ injectTerminal(terminal);
+ terminal.start();
+ assertTrue(buildingTerminal.await(10, SECONDS), "FastTerminal
build thread must start");
+
+ // Run logging() on a separate thread — it will block inside
configure() when
+ // toAnsi() calls FastTerminal.getType() → getTerminal() →
terminal.get().
+ MavenCli cli = new MavenCli();
+ CliRequest request = new CliRequest(new String[]
{"-Dstyle.color=always"}, null);
+ cli.cli(request);
+ cli.properties(request);
+ FutureTask<Void> logging = new FutureTask<>(() -> {
+ cli.logging(request);
+ return null;
+ });
+ loggingThread = new Thread(logging, "logging-initialization-test");
+ loggingThread.setDaemon(true);
+ loggingThread.start();
+
+ // Wait until the logging thread is blocked on the terminal's
CompletableFuture.
+ // At that point, config.init() has already captured earlyStream
(it runs before
+ // configure() which is where the block occurs).
+ awaitThreadState(loggingThread, Thread.State.WAITING, 10_000);
+
+ // Release the terminal — the consumer sets
System.out=terminalStream, but the
+ // logger has already cached earlyStream in config.init().
+ releaseTerminal.countDown();
+ logging.get(10, SECONDS);
+
+ // The logger must still write to earlyStream.
+
LoggerFactory.getLogger(MavenCliLoggingTest.class).warn("terminal-output-marker");
+ assertTrue(
+
earlyOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
+ "Logger must write to the stream that was active when
logging() ran with -color=always");
+ assertFalse(
+
terminalOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
+ "Logger must not switch to the stream installed after
logging() completed");
+ } finally {
+ releaseTerminal.countDown();
+ if (loggingThread != null) {
+ loggingThread.join(10_000);
+ }
+ }
+ }
+
+ /**
+ * When {@code -l <logfile>} is used, {@code logging()} must call
+ * {@link MessageUtils#awaitTerminalInitialization()} before redirecting
{@code System.out}
+ * to the log file. Without the await, the terminal's installed consumer
(which may call
+ * {@code System.setOut}) could race with the log-file redirect, causing
logs to leak to
+ * the console instead of the log file (see
+ * <a href="https://github.com/apache/maven/issues/12188">#12188</a>).
+ * <p>
+ * This test verifies that the terminal consumer fires <em>before</em>
{@code System.out} is
+ * redirected to the log file, so the consumer cannot overwrite the
log-file redirect.
+ */
+ @Test
+ void logFileBranchAwaitsTerminalBeforeRedirect(@TempDir Path tempDir)
throws Exception {
+ PrintStream originalOut = System.out;
+
+ Path logFile = tempDir.resolve("maven.log");
+ Files.writeString(logFile, "");
+
+ CountDownLatch buildingTerminal = new CountDownLatch(1);
+ CountDownLatch releaseTerminal = new CountDownLatch(1);
+ // Set by the terminal consumer; true means the consumer fired before
System.out was
+ // redirected to the log file — which is the correct behaviour: the
consumer fires
+ // BEFORE the log redirect, so it cannot overwrite it.
+ AtomicBoolean consumerFiredBeforeRedirect = new AtomicBoolean(false);
+ Thread loggingThread = null;
+ try {
+ FastTerminal terminal = new FastTerminal(
+ () -> {
+ buildingTerminal.countDown();
+ if (!releaseTerminal.await(10, SECONDS)) {
+ throw new IllegalStateException("Terminal
installation was not released");
+ }
+ return mock(TerminalExt.class, RETURNS_DEEP_STUBS);
+ },
+ installed -> {
+ // The consumer fires as part of terminal.complete()
inside the build thread.
+ // If awaitTerminalInitialization() was called, the
consumer fires BEFORE
+ // logging() redirects System.out to the log file. We
detect this by
+ // checking whether System.out is still the original
stream at this point.
+ consumerFiredBeforeRedirect.set(System.out ==
originalOut);
+ });
+ injectTerminal(terminal);
+ terminal.start();
+ assertTrue(buildingTerminal.await(10, SECONDS), "FastTerminal
build thread must start");
+
+ MavenCli cli = new MavenCli();
+ CliRequest request =
+ new CliRequest(new String[] {"-l",
logFile.toAbsolutePath().toString()}, null);
+ cli.cli(request);
+ cli.properties(request);
+ FutureTask<Void> logging = new FutureTask<>(() -> {
+ cli.logging(request);
+ return null;
+ });
+ loggingThread = new Thread(logging, "logging-initialization-test");
+ loggingThread.setDaemon(true);
+ loggingThread.start();
+
+ // Release the terminal; logging() will unblock from
awaitTerminalInitialization(),
+ // the consumer fires, then the redirect happens.
+ releaseTerminal.countDown();
+ logging.get(10, SECONDS);
+
+ // The consumer must have fired before System.out was redirected
to the log file.
+ assertTrue(
+ consumerFiredBeforeRedirect.get(),
+ "Terminal consumer must fire before System.out is
redirected to the log file; "
+ + "if it fires after, it could overwrite the
log-file redirect (#12188)");
+
+ // After logging() returns, System.out must be redirected to the
log file (not original).
+ assertFalse(
+ System.out == originalOut,
+ "After logging() with -l, System.out must be redirected to
the log file");
+ } finally {
+ releaseTerminal.countDown();
+ if (loggingThread != null) {
+ loggingThread.join(10_000);
+ }
+ // Close the PrintStream wrapping maven.log so @TempDir can delete
the temp directory on Windows.
+ // An open FileOutputStream prevents directory deletion on Windows.
+ PrintStream logStream = System.out;
+ System.setOut(originalOut);
+ if (logStream != originalOut) {
+ logStream.close();
+ }
+ }
+ }
+
+ /**
+ * When color is set to {@code never} or {@code auto} (batch mode), {@code
logging()} must call
+ * {@code awaitTerminalInitialization()} before activating the logging
configuration, so that
+ * the terminal consumer has already swapped {@code System.out} before the
logger caches it.
+ * This prevents logs from going to a stale stream instead of the
terminal-wrapped one.
+ * <p>
+ * Unlike the {@code color=always} test, this test verifies that the
logger caches the
+ * <em>terminal</em> stream, not the early stream. The held-back {@link
FastTerminal}
+ * approach works cleanly here: {@code logging()} calls {@code
awaitTerminalInitialization()}
+ * which blocks until the terminal is released. When released, the
consumer swaps
+ * {@code System.out}, then {@code config.init()} captures the new stream.
+ */
+ @Test
+ void cachesOutputAfterTerminalInstallationWithColorDisabled() throws
Exception {
+ cachesOutputAfterTerminalInstallation("never");
+ }
+
+ @Test
+ void cachesOutputAfterTerminalInstallationInBatchMode() throws Exception {
+ cachesOutputAfterTerminalInstallation("batch");
+ }
+
+ private void cachesOutputAfterTerminalInstallation(String color) throws
Exception {
+ CountDownLatch buildingTerminal = new CountDownLatch(1);
+ CountDownLatch releaseTerminal = new CountDownLatch(1);
+ ByteArrayOutputStream earlyOutput = new ByteArrayOutputStream();
+ ByteArrayOutputStream terminalOutput = new ByteArrayOutputStream();
+ Thread loggingThread = null;
+ try (PrintStream earlyStream = new PrintStream(earlyOutput, true,
UTF_8.name());
+ PrintStream terminalStream = new PrintStream(terminalOutput,
true, UTF_8.name())) {
+ System.setProperty(MavenBaseLogger.LEGACY_PREFIX +
"cacheOutputStream", "true");
+ System.setProperty(MavenBaseLogger.LEGACY_PREFIX + "logFile",
"System.out");
+ System.setOut(earlyStream);
+ activateSlf4j();
+
+ FastTerminal terminal = new FastTerminal(
+ () -> {
+ buildingTerminal.countDown();
+ if (!releaseTerminal.await(10, SECONDS)) {
+ throw new IllegalStateException("Terminal
installation was not released");
+ }
+ return mock(TerminalExt.class, RETURNS_DEEP_STUBS);
+ },
+ installed -> System.setOut(terminalStream));
+ // Inject the FastTerminal directly into MessageUtils.terminal
before starting the
+ // build thread, to avoid calling systemInstall(Terminal) which
also creates a LineReader
+ // from the terminal — that would call FastTerminal.getTerminal()
and block.
+ injectTerminal(terminal);
+ terminal.start();
+ assertTrue(buildingTerminal.await(10, SECONDS));
+
+ MavenCli cli = new MavenCli();
+ CliRequest request = new CliRequest(
+ "batch".equals(color) ? new String[] {"-B"} : new String[]
{"-Dstyle.color=" + color}, null);
+ cli.cli(request);
+ cli.properties(request);
+ FutureTask<Void> logging = new FutureTask<>(() -> {
+ cli.logging(request);
+ return null;
+ });
+ loggingThread = new Thread(logging, "logging-initialization-test");
+ loggingThread.setDaemon(true);
+ loggingThread.start();
+
+ // Wait until the logging thread is blocked on
awaitTerminalInitialization() →
+ // FastTerminal.getTerminal() → CompletableFuture.get(). At this
point,
+ // config.init() has NOT yet run (it comes after
awaitTerminalInitialization()).
+ awaitThreadState(loggingThread, Thread.State.WAITING, 10_000);
+
+ // Release the terminal — the consumer sets
System.out=terminalStream.
+ // awaitTerminalInitialization() returns, then config.init()
captures terminalStream.
+ releaseTerminal.countDown();
+ logging.get(10, SECONDS);
+
+
LoggerFactory.getLogger(MavenCliLoggingTest.class).warn("terminal-output-marker");
+ assertTrue(
+
terminalOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
+ "Logger must write to the stream installed by the terminal
consumer");
+ assertFalse(
+
earlyOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
+ "Logger must not write to the early stream that was active
before terminal installation");
+ } finally {
+ releaseTerminal.countDown();
+ if (loggingThread != null) {
+ loggingThread.join(10_000);
+ }
+ }
+ }
+
+ /**
+ * Waits until the given thread enters the expected state or the timeout
expires.
+ * Used to detect when a thread is blocked on {@code
CompletableFuture.get()} inside
+ * {@code FastTerminal.getTerminal()}. This is more reliable than a fixed
sleep and
+ * avoids depending on platform-specific scheduling behavior.
+ *
+ * @param thread the thread to monitor
+ * @param expected the expected thread state (typically {@link
Thread.State#WAITING})
+ * @param timeoutMs maximum time to wait in milliseconds
+ */
+ private static void awaitThreadState(Thread thread, Thread.State expected,
long timeoutMs)
+ throws InterruptedException {
+ long deadline = System.nanoTime() + timeoutMs * 1_000_000L;
+ while (thread.getState() != expected) {
+ if (System.nanoTime() > deadline) {
+ throw new AssertionError("Thread " + thread.getName() + " did
not reach state " + expected + " within "
+ + timeoutMs + "ms; actual state: " +
thread.getState());
+ }
+ Thread.sleep(10);
+ }
+ }
+
+ /**
+ * Injects the given terminal directly into {@link MessageUtils#terminal}
without creating a
+ * {@code LineReader} from it. This avoids calling {@link
MessageUtils#systemInstall(Terminal)}
+ * which on master tries to build a {@code LineReader} — that calls
+ * {@link FastTerminal#getTerminal()} which blocks until the build thread
completes.
+ */
+ private static void injectTerminal(Terminal terminal) throws Exception {
+ Field field = MessageUtils.class.getDeclaredField("terminal");
+ field.setAccessible(true);
+ field.set(null, terminal);
+ }
+
+ /**
+ * Reads the raw {@code colorEnabled} field from {@link MessageUtils}
without requiring a
+ * terminal to be installed (unlike {@link MessageUtils#isColorEnabled()}
which also checks
+ * {@code terminal != null}).
+ */
+ private static boolean getColorEnabled() throws Exception {
+ Field field = MessageUtils.class.getDeclaredField("colorEnabled");
+ field.setAccessible(true);
+ return (boolean) field.get(null);
+ }
+
+ private static void setColorEnabled(boolean value) throws Exception {
+ Field field = MessageUtils.class.getDeclaredField("colorEnabled");
+ field.setAccessible(true);
+ field.set(null, value);
+ }
+
+ private static Terminal getTerminalField() throws Exception {
+ Field field = MessageUtils.class.getDeclaredField("terminal");
+ field.setAccessible(true);
+ return (Terminal) field.get(null);
+ }
+
+ private static void activateSlf4j() {
+ Slf4jConfiguration config =
Slf4jConfigurationFactory.getConfiguration(LoggerFactory.getILoggerFactory());
+ config.activate();
+ }
+
+ private static void restoreProperty(String name, String value) {
+ if (value == null) {
+ System.clearProperty(name);
+ } else {
+ System.setProperty(name, value);
+ }
+ }
+}
diff --git
a/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
b/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
index 26da7ec45a..38e09d19ef 100644
--- a/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
+++ b/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
@@ -110,6 +110,20 @@ private static void doSystemUninstall() {
}
}
+ /**
+ * Blocks until the asynchronous terminal installation completes.
+ * Call this before redirecting {@code System.out}/{@code System.err} to
avoid the terminal
+ * thread overwriting your redirection, and before activating logging
configuration to ensure
+ * it caches the correct output stream.
+ *
+ * @see <a href="https://github.com/apache/maven/issues/12188">#12188</a>
+ */
+ public static void awaitTerminalInitialization() {
+ if (terminal instanceof FastTerminal fastTerminal) {
+ fastTerminal.getTerminal();
+ }
+ }
+
public static void setColorEnabled(boolean enabled) {
colorEnabled = enabled;
}
diff --git
a/impl/maven-logging/src/main/java/org/apache/maven/slf4j/SimpleLoggerConfiguration.java
b/impl/maven-logging/src/main/java/org/apache/maven/slf4j/SimpleLoggerConfiguration.java
index 27776f1e77..fe5654bfa7 100644
---
a/impl/maven-logging/src/main/java/org/apache/maven/slf4j/SimpleLoggerConfiguration.java
+++
b/impl/maven-logging/src/main/java/org/apache/maven/slf4j/SimpleLoggerConfiguration.java
@@ -93,6 +93,8 @@ public class SimpleLoggerConfiguration {
void init() {
// Reset state before initialization
+ defaultLogLevel = DEFAULT_LOG_LEVEL_DEFAULT;
+ logFile = LOG_FILE_DEFAULT;
dateFormatter = null;
loadProperties();