This is an automated email from the ASF dual-hosted git repository. slachiewicz pushed a commit to branch plugin-logger-4.0 in repository https://gitbox.apache.org/repos/asf/maven.git
commit bef27a6be65d9bf8b4ba0aa894c5fb2a1697062f Author: Sylwester Lachiewicz <[email protected]> AuthorDate: Wed Nov 18 10:34:15 2026 +0100 Adapt Logger API for Maven 4.0 and replace org.apache.maven.api.plugin.Log - Wire maven-api-log into maven-api and maven-api-core - Adjust @since to 4.0.0 and omit LoggerManager/LogSink/LogEvent (targeted for 4.2 in #13832) - Remove org.apache.maven.api.plugin.Log and replace DefaultLog with DefaultLogger backed by SLF4J - Update MojoExecutionScopeModule, DefaultMavenPluginManager, DefaultBuildPluginManager, MojoExtension, and IT fixtures to use org.apache.maven.api.logging.Logger --- api/maven-api-core/pom.xml | 4 + .../main/java/org/apache/maven/api/plugin/Log.java | 265 --------------- .../apache/maven/api/di/MojoExecutionScoped.java | 2 +- api/maven-api-log/pom.xml | 4 +- api/maven-api-log/src/main/java/module-info.java | 26 -- .../apache/maven/api/logging/LogEventBuilder.java | 2 +- .../org/apache/maven/api/logging/LogLevel.java | 2 +- .../java/org/apache/maven/api/logging/Logger.java | 45 +-- .../org/apache/maven/api/logging/package-info.java | 94 +----- api/pom.xml | 1 + .../scope/internal/MojoExecutionScopeModule.java | 6 +- .../org/apache/maven/internal/impl/DefaultLog.java | 245 -------------- .../apache/maven/internal/impl/DefaultLogger.java | 354 +++++++++++++++++++++ .../maven/plugin/DefaultBuildPluginManager.java | 6 +- .../plugin/internal/DefaultMavenPluginManager.java | 6 +- .../apache/maven/internal/impl/DefaultLogTest.java | 196 ------------ .../maven/internal/impl/DefaultLoggerTest.java | 91 ++++++ .../apache/maven/testing/plugin/MojoExtension.java | 10 +- .../com/gitlab/tkslaw/ditests/DITestsMojoBase.java | 4 +- .../org/apache/maven/its/gh11378/TestMojo.java | 4 +- .../org/apache/maven/plugin/coreit/TouchMojo.java | 4 +- .../org/apache/maven/its/mng12534/TouchMojo.java | 4 +- .../java/org/apache/maven/plugins/HelloMojo.java | 4 +- .../maven/its/mng8572/extension/NoOpMojo.java | 4 +- pom.xml | 5 + 25 files changed, 494 insertions(+), 894 deletions(-) diff --git a/api/maven-api-core/pom.xml b/api/maven-api-core/pom.xml index 104d6375b7..b4e7c92e4a 100644 --- a/api/maven-api-core/pom.xml +++ b/api/maven-api-core/pom.xml @@ -35,6 +35,10 @@ <groupId>org.apache.maven</groupId> <artifactId>maven-api-annotations</artifactId> </dependency> + <dependency> + <groupId>org.apache.maven</groupId> + <artifactId>maven-api-log</artifactId> + </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-api-di</artifactId> diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java b/api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java deleted file mode 100644 index a50d86c48b..0000000000 --- a/api/maven-api-core/src/main/java/org/apache/maven/api/plugin/Log.java +++ /dev/null @@ -1,265 +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.api.plugin; - -import java.util.function.Supplier; - -import org.apache.maven.api.annotations.Experimental; -import org.apache.maven.api.annotations.Provider; - -/** - * This interface supplies the API for providing feedback to the user from the {@code Mojo}, - * using standard Maven channels. - * There should be no big surprises here, although you may notice that the methods accept - * <code>java.lang.CharSequence</code> rather than <code>java.lang.String</code>. This is provided mainly as a - * convenience, to enable developers to pass things like <code>java.lang.StringBuffer</code> directly into the logger, - * rather than formatting first by calling <code>toString()</code>. - * - * @since 4.0.0 - */ -@Experimental -@Provider -public interface Log { - /** - * {@return true if the <b>trace</b> error level is enabled} - * <p> - * The default implementation returns {@code false} for backward - * compatibility with existing {@code Log} implementations. - */ - default boolean isTraceEnabled() { - return false; - } - - /** - * Sends a message to the user in the <b>trace</b> error level. - * <p> - * Trace is the most verbose level, intended for Maven core internals - * such as resolver negotiation, model interpolation, and lifecycle - * ordering details. Use {@link #debug(CharSequence)} instead for - * messages that help <em>users</em> investigate their build - * (e.g. why a module was recompiled). - * <p> - * The default implementation is a no-op for backward compatibility. - * - * @param content the message to log - */ - default void trace(CharSequence content) {} - - /** - * Sends a message (and accompanying exception) to the user at the <b>trace</b> error level. - * The error's stacktrace will be output when this error level is enabled. - * <p> - * The default implementation is a no-op for backward compatibility. - * - * @param content the message to log - * @param error the error that caused this log - */ - default void trace(CharSequence content, Throwable error) {} - - /** - * Sends an exception to the user in the <b>trace</b> error level. - * The stack trace for this exception will be output when this error level is enabled. - * <p> - * The default implementation is a no-op for backward compatibility. - * - * @param error the error that caused this log - */ - default void trace(Throwable error) {} - - /** - * Sends a lazily-computed message in 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. - * - * @param content the message supplier - */ - default void trace(Supplier<String> content) {} - - /** - * Sends a lazily-computed message (and accompanying exception) in 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. - * - * @param content the message supplier - * @param error the error that caused this log - */ - default void trace(Supplier<String> content, Throwable error) {} - - /** - * {@return true if the <b>debug</b> error level is enabled} - */ - boolean isDebugEnabled(); - - /** - * Sends a message to the user in the <b>debug</b> error level. - * <p> - * Debug is intended for messages that help <em>users</em> investigate - * their build — for example, why a module was recompiled or what - * classpath was resolved. For Maven core internals, use - * {@link #trace(CharSequence)} instead. - * - * @param content the message to log - */ - void debug(CharSequence content); - - /** - * Sends a message (and accompanying exception) to the user in the <b>debug</b> error level. - * The error's stacktrace will be output when this error level is enabled. - * - * @param content the message to log - * @param error the error that caused this log - */ - void debug(CharSequence content, Throwable error); - - /** - * Sends an exception to the user in the <b>debug</b> error level. - * The stack trace for this exception will be output when this error level is enabled. - * - * @param error the error that caused this log - */ - void debug(Throwable error); - - void debug(Supplier<String> content); - - void debug(Supplier<String> content, Throwable error); - - /** - * {@return true if the <b>info</b> error level is enabled} - */ - boolean isInfoEnabled(); - - /** - * Sends a message to the user in the <b>info</b> error level. - * - * @param content the message to log - */ - void info(CharSequence content); - - /** - * Sends a message (and accompanying exception) to the user in the <b>info</b> error level. - * The error's stacktrace will be output when this error level is enabled. - * - * @param content the message to log - * @param error the error that caused this log - */ - void info(CharSequence content, Throwable error); - - /** - * Sends an exception to the user in the <b>info</b> error level. - * The stack trace for this exception will be output when this error level is enabled. - * - * @param error the error that caused this log - */ - void info(Throwable error); - - void info(Supplier<String> content); - - void info(Supplier<String> content, Throwable error); - - /** - * {@return true if the <b>warn</b> error level is enabled} - */ - boolean isWarnEnabled(); - - /** - * Sends a message to the user in the <b>warn</b> error level. - * - * @param content the message to log - */ - void warn(CharSequence content); - - /** - * Sends a message (and accompanying exception) to the user in the <b>warn</b> error level. - * The error's stacktrace will be output when this error level is enabled. - * - * @param content the message to log - * @param error the error that caused this log - */ - void warn(CharSequence content, Throwable error); - - /** - * Sends an exception to the user in the <b>warn</b> error level. - * The stack trace for this exception will be output when this error level is enabled. - * - * @param error the error that caused this log - */ - void warn(Throwable error); - - void warn(Supplier<String> content); - - void warn(Supplier<String> content, Throwable error); - - /** - * {@return true if the <b>error</b> error level is enabled} - */ - boolean isErrorEnabled(); - - /** - * Sends a message to the user in the <b>error</b> error level. - * - * @param content the message to log - */ - void error(CharSequence content); - - /** - * Sends a message (and accompanying exception) to the user in the <b>error</b> error level. - * The error's stacktrace will be output when this error level is enabled. - * - * @param content the message to log - * @param error the error that caused this log - */ - void error(CharSequence content, Throwable error); - - /** - * Sends an exception to the user in the <b>error</b> error level. - * The stack trace for this exception will be output when this error level is enabled. - * - * @param error the error that caused this log - */ - void error(Throwable error); - - void error(Supplier<String> content); - - void error(Supplier<String> content, Throwable error); - - /** - * Returns a child logger whose name is derived from this logger's name - * by appending a dot and the given suffix. - * - * <p>For example, if a plugin's logger is named - * {@code "org.apache.maven.plugins.compiler.CompilerMojo"}, - * then {@code child("diagnostics")} returns a logger named - * {@code "org.apache.maven.plugins.compiler.CompilerMojo.diagnostics"}. - * This lets sub-components log under an independently filterable name - * without requiring a separate injection point.</p> - * - * <p>The default implementation returns {@code this}, so existing - * {@code Log} implementations continue to work without changes. - * Implementations that wrap a hierarchical logging backend (such as - * SLF4J) should override this to create a real child logger.</p> - * - * @param name the suffix to append (must not be {@code null} or blank) - * @return a child logger — never {@code null} - */ - default Log child(String name) { - return this; - } -} diff --git a/api/maven-api-di/src/main/java/org/apache/maven/api/di/MojoExecutionScoped.java b/api/maven-api-di/src/main/java/org/apache/maven/api/di/MojoExecutionScoped.java index 729ec5e107..141936b656 100644 --- a/api/maven-api-di/src/main/java/org/apache/maven/api/di/MojoExecutionScoped.java +++ b/api/maven-api-di/src/main/java/org/apache/maven/api/di/MojoExecutionScoped.java @@ -34,7 +34,7 @@ * <ul> * <li>{@code org.apache.maven.api.MojoExecution}</li> * <li>{@code org.apache.maven.api.Project}</li> - * <li>{@code org.apache.maven.api.plugin.Log}</li> + * <li>{@code org.apache.maven.api.logging.Logger}</li> * </ul> * * @since 4.0.0 diff --git a/api/maven-api-log/pom.xml b/api/maven-api-log/pom.xml index f55f7b4ed1..14001aab9c 100644 --- a/api/maven-api-log/pom.xml +++ b/api/maven-api-log/pom.xml @@ -23,12 +23,12 @@ <parent> <groupId>org.apache.maven</groupId> <artifactId>maven-api</artifactId> - <version>4.2.0-SNAPSHOT</version> + <version>4.0.0-SNAPSHOT</version> </parent> <artifactId>maven-api-log</artifactId> <name>Maven 4 API :: Logging</name> - <description>Maven 4 API - Unified Logging API (Logger, LogEventBuilder, LogLevel, LogEvent, LogSink).</description> + <description>Maven 4 API - Unified Logging API (Logger, LogEventBuilder, LogLevel).</description> <properties> <javaModuleName>org.apache.maven.api.logging</javaModuleName> diff --git a/api/maven-api-log/src/main/java/module-info.java b/api/maven-api-log/src/main/java/module-info.java deleted file mode 100644 index 8dc04d31b7..0000000000 --- a/api/maven-api-log/src/main/java/module-info.java +++ /dev/null @@ -1,26 +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. - */ - -module org.apache.maven.api.logging { - requires transitive org.apache.maven.api.annotations; - - exports org.apache.maven.api.logging; - - uses org.apache.maven.api.logging.LoggerManager; -} diff --git a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogEventBuilder.java b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogEventBuilder.java index 250485ce58..a85ca4aafc 100644 --- a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogEventBuilder.java +++ b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogEventBuilder.java @@ -39,7 +39,7 @@ * .log("Compiling {} source files", count); * }</pre> * - * @since 4.2.0 + * @since 4.0.0 */ @Experimental public interface LogEventBuilder { diff --git a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogLevel.java b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogLevel.java index 5620dc45a3..5aa5865be9 100644 --- a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogLevel.java +++ b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/LogLevel.java @@ -24,7 +24,7 @@ /** * Log severity levels. * - * @since 4.2.0 + * @since 4.0.0 */ @Experimental @Immutable diff --git a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/Logger.java b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/Logger.java index 58f43a5bda..71df958256 100644 --- a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/Logger.java +++ b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/Logger.java @@ -50,7 +50,7 @@ * log.warn("Deprecated configuration key: {}", key, e); * }</pre> * - * @since 4.2.0 + * @since 4.0.0 */ @Experimental @Provider @@ -336,55 +336,12 @@ default void error(@Nonnull Supplier<String> message, @Nullable Throwable t) { atError().withThrowable(t).log(message); } - // ---- Static factory ---- - - /** - * Returns a {@code Logger} for the given class, using the fully-qualified - * class name as the logger name. - * <p> - * Shorthand for {@code LoggerManager.get().getLogger(clazz)}. - * Safe to call at any point — even during early bootstrap before the - * real logging implementation is available. In that case, a bootstrap - * logger is returned that buffers events until the real implementation - * is discovered. - * - * @param clazz the class whose name is used as the logger name, never {@code null} - * @return a {@code Logger} instance, never {@code null} - * @since 4.2.0 - */ - @Nonnull - static Logger of(@Nonnull Class<?> clazz) { - return LoggerManager.get().getLogger(clazz); - } - - /** - * Returns a {@code Logger} with the given name. - * <p> - * Shorthand for {@code LoggerManager.get().getLogger(name)}. Intended for - * framework code or dynamic logger names. - * Safe to call at any point — even during early bootstrap. - * - * @param name the logger name, never {@code null} - * @return a {@code Logger} instance, never {@code null} - * @since 4.2.0 - */ - @Nonnull - static Logger of(@Nonnull String name) { - return LoggerManager.get().getLogger(name); - } - // ---- Child logger ---- /** * Returns a child logger whose name is this logger's name with * {@code "." + name} appended. * - * <p>If this logger was constructed with a {@code projectId} and/or {@code mojoId} - * (as is the case for DI-injected mojo loggers), those values are propagated to the - * child so sub-component events are automatically tagged with the correct project and - * mojo execution. Loggers obtained via {@link #of(Class)} or {@link #of(String)} have - * no such context, and the child will likewise carry {@code null} for those fields.</p> - * * @param name the child suffix, never {@code null} * @return a child {@code Logger} instance, never {@code null} */ diff --git a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/package-info.java b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/package-info.java index 8ad23889b6..4267acc26e 100644 --- a/api/maven-api-log/src/main/java/org/apache/maven/api/logging/package-info.java +++ b/api/maven-api-log/src/main/java/org/apache/maven/api/logging/package-info.java @@ -19,104 +19,24 @@ /** * Maven unified logging API — a first-class, SLF4J-free logging facade for - * plugins, extensions, and Maven internals. - * - * <h2>Overview</h2> - * <p> - * This package replaces the older {@code org.apache.maven.api.plugin.Log} - * plugin facade and the SLF4J-backed CLI logger with a single, consistent - * API that works uniformly across mojos, extensions, and Maven's own - * internal components. - * </p> + * plugins and extensions. * * <h2>Core types</h2> * <dl> * <dt>{@link org.apache.maven.api.logging.Logger}</dt> - * <dd>The primary logging interface. Obtained via {@link org.apache.maven.api.logging.Logger#of(Class)} - * or injected by the container. Supports a fluent builder API ({@code atInfo()…log(…)}) - * as well as SLF4J-style convenience methods ({@code info(…)}, {@code warn(…)}, etc.). - * Instances are safe to hold in static or instance fields — context such as - * {@code projectId} and {@code mojoId} is resolved from a per-thread - * {@link org.apache.maven.api.logging.LogSink} at dispatch time.</dd> + * <dd>The primary logging interface injected by the container. Supports a fluent builder + * API ({@code atInfo()...log(...)}) as well as SLF4J-style convenience methods + * ({@code info(...)}, {@code warn(...)}, etc.).</dd> * * <dt>{@link org.apache.maven.api.logging.LogEventBuilder}</dt> - * <dd>Fluent builder for a single log event. Obtained from {@code Logger.atLevel()}. - * Accumulates level, message template, arguments, throwable, and key-value pairs - * before dispatching via {@code log(…)}. When the target level is disabled, returns - * a no-op singleton (zero allocations).</dd> - * - * <dt>{@link org.apache.maven.api.logging.LogEvent}</dt> - * <dd>Immutable record of a single log event. Carries the logger name, level, raw - * message template, arguments (lazy formatting), throwable, and optional - * {@code projectId} / {@code mojoId} context. Passed to {@link org.apache.maven.api.logging.LogSink} - * for consumption.</dd> - * - * <dt>{@link org.apache.maven.api.logging.LogSink}</dt> - * <dd>Consumer of {@link org.apache.maven.api.logging.LogEvent}s. This is the primary - * extension point for embedders and build tools: implement {@code LogSink} and register - * it via {@link org.apache.maven.api.logging.LoggerManager#setLogSink(LogSink)} (or via - * {@link java.util.ServiceLoader} discovery) to redirect all Maven log output to any - * destination — a UI, a structured log store, a test buffer, etc.</dd> - * - * <dt>{@link org.apache.maven.api.logging.LoggerManager}</dt> - * <dd>Central control surface: obtains loggers, installs the active sink, configures - * root and per-logger levels, and tracks the highest severity reached (for - * {@code --fail-on-severity}). Accessed via {@link org.apache.maven.api.logging.LoggerManager#get()}, - * which is set up by Maven before any logging occurs.</dd> + * <dd>Fluent builder for a single log event, obtained from {@code Logger.atLevel()}. + * When the target level is disabled, returns a no-op singleton (zero allocations).</dd> * * <dt>{@link org.apache.maven.api.logging.LogLevel}</dt> * <dd>Ordered severity enumeration: {@code TRACE}, {@code DEBUG}, {@code INFO}, * {@code WARN}, {@code ERROR}.</dd> * </dl> * - * <h2>Getting a logger</h2> - * <p> - * The typical pattern for plugin and extension code is: - * </p> - * <pre>{@code - * private final Logger log = Logger.of(MyComponent.class); - * }</pre> - * <p> - * {@code Logger.of()} is safe to call at any point, even during early bootstrap - * before the real logging implementation is available. In that case a bootstrap - * logger is returned that buffers events until the real implementation is - * discovered via {@link java.util.ServiceLoader} or installed via - * {@link org.apache.maven.api.logging.LoggerManager#set(LoggerManager)}. - * </p> - * <p> - * Framework code that does not have a class reference can use the string overload: - * </p> - * <pre>{@code - * Logger log = Logger.of("org.apache.maven.my-component"); - * }</pre> - * - * <h2>Logging events</h2> - * <p>Fluent API (preferred — enables lazy formatting and structured key-value pairs):</p> - * <pre>{@code - * log.atInfo() - * .withKeyValue("artifact", artifact.getId()) - * .log("Resolved {} files", count); - * }</pre> - * <p>Convenience methods (SLF4J-style shorthand):</p> - * <pre>{@code - * log.info("Compiling {} source files", count); - * log.warn("Deprecated key: {}", key, e); - * }</pre> - * - * <h2>Embedder integration</h2> - * <p> - * To redirect Maven log output, implement {@link org.apache.maven.api.logging.LogSink} - * and either: - * </p> - * <ul> - * <li>Register it via {@code ServiceLoader} — place a - * {@code META-INF/services/org.apache.maven.api.logging.LogSink} file on the - * classpath pointing to your implementation. Maven discovers it before any - * logging occurs.</li> - * <li>Or call {@link org.apache.maven.api.logging.LoggerManager#setLogSink(LogSink)} - * programmatically during embedder setup.</li> - * </ul> - * - * @since 4.2.0 + * @since 4.0.0 */ package org.apache.maven.api.logging; diff --git a/api/pom.xml b/api/pom.xml index ba5c47f3a1..049d4bb976 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -40,6 +40,7 @@ <module>maven-api-settings</module> <module>maven-api-toolchain</module> <module>maven-api-metadata</module> + <module>maven-api-log</module> <module>maven-api-core</module> <module>maven-api-spi</module> <module>maven-api-cli</module> diff --git a/impl/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java b/impl/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java index a477ec868c..b7fbcfbb57 100644 --- a/impl/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java +++ b/impl/maven-core/src/main/java/org/apache/maven/execution/scope/internal/MojoExecutionScopeModule.java @@ -19,7 +19,7 @@ package org.apache.maven.execution.scope.internal; import com.google.inject.AbstractModule; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.execution.scope.MojoExecutionScoped; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.project.MavenProject; @@ -45,8 +45,8 @@ protected void configure() { bind(MojoExecution.class) .toProvider(MojoExecutionScope.seededKeyProvider(MojoExecution.class)) .in(scope); - bind(Log.class) - .toProvider(MojoExecutionScope.seededKeyProvider(Log.class)) + bind(Logger.class) + .toProvider(MojoExecutionScope.seededKeyProvider(Logger.class)) .in(scope); bind(org.apache.maven.api.Project.class) .toProvider(MojoExecutionScope.seededKeyProvider(org.apache.maven.api.Project.class)) diff --git a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java deleted file mode 100644 index b1cf40cc40..0000000000 --- a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLog.java +++ /dev/null @@ -1,245 +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.internal.impl; - -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 { - private final Logger logger; - - public DefaultLog(Logger logger) { - this.logger = requireNonNull(logger); - } - - @Override - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - @Override - public void trace(CharSequence content) { - if (isTraceEnabled()) { - logger.trace(toString(content)); - } - } - - @Override - public void trace(CharSequence content, Throwable error) { - if (isTraceEnabled()) { - logger.trace(toString(content), error); - } - } - - @Override - public void trace(Throwable error) { - if (isTraceEnabled()) { - logger.trace("", error); - } - } - - @Override - public void trace(Supplier<String> content) { - if (isTraceEnabled()) { - logger.trace(content.get()); - } - } - - @Override - public void trace(Supplier<String> content, Throwable error) { - if (isTraceEnabled()) { - logger.trace(content.get(), error); - } - } - - @Override - public void debug(CharSequence content) { - if (isDebugEnabled()) { - logger.debug(toString(content)); - } - } - - @Override - public void debug(CharSequence content, Throwable error) { - if (isDebugEnabled()) { - logger.debug(toString(content), error); - } - } - - @Override - public void debug(Throwable error) { - if (isDebugEnabled()) { - logger.debug("", error); - } - } - - @Override - public void debug(Supplier<String> content) { - if (isDebugEnabled()) { - logger.debug(content.get()); - } - } - - @Override - public void debug(Supplier<String> content, Throwable error) { - if (isDebugEnabled()) { - logger.debug(content.get(), error); - } - } - - @Override - public void info(CharSequence content) { - if (isInfoEnabled()) { - logger.info(toString(content)); - } - } - - @Override - public void info(CharSequence content, Throwable error) { - if (isInfoEnabled()) { - logger.info(toString(content), error); - } - } - - @Override - public void info(Throwable error) { - if (isInfoEnabled()) { - logger.info("", error); - } - } - - @Override - public void info(Supplier<String> content) { - if (isInfoEnabled()) { - logger.info(content.get()); - } - } - - @Override - public void info(Supplier<String> content, Throwable error) { - if (isInfoEnabled()) { - logger.info(content.get(), error); - } - } - - @Override - public void warn(CharSequence content) { - if (isWarnEnabled()) { - logger.warn(toString(content)); - } - } - - @Override - public void warn(CharSequence content, Throwable error) { - if (isWarnEnabled()) { - logger.warn(toString(content), error); - } - } - - @Override - public void warn(Throwable error) { - if (isWarnEnabled()) { - logger.warn("", error); - } - } - - @Override - public void warn(Supplier<String> content) { - if (isWarnEnabled()) { - logger.warn(content.get()); - } - } - - @Override - public void warn(Supplier<String> content, Throwable error) { - if (isWarnEnabled()) { - logger.warn(content.get(), error); - } - } - - @Override - public void error(CharSequence content) { - if (isErrorEnabled()) { - logger.error(toString(content)); - } - } - - @Override - public void error(CharSequence content, Throwable error) { - if (isErrorEnabled()) { - logger.error(toString(content), error); - } - } - - @Override - public void error(Throwable error) { - if (isErrorEnabled()) { - logger.error("", error); - } - } - - @Override - public void error(Supplier<String> content) { - if (isErrorEnabled()) { - logger.error(content.get()); - } - } - - @Override - public void error(Supplier<String> content, Throwable error) { - if (isErrorEnabled()) { - logger.error(content.get(), error); - } - } - - @Override - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - @Override - public Log child(String name) { - requireNonNull(name, "name"); - return new DefaultLog(LoggerFactory.getLogger(logger.getName() + "." + name)); - } - - private String toString(CharSequence content) { - return content != null ? content.toString() : ""; - } -} diff --git a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLogger.java b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLogger.java new file mode 100644 index 0000000000..75e74dadf4 --- /dev/null +++ b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLogger.java @@ -0,0 +1,354 @@ +/* + * 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.impl; + +import java.util.function.Supplier; + +import org.apache.maven.api.annotations.Nonnull; +import org.apache.maven.api.logging.LogEventBuilder; +import org.apache.maven.api.logging.LogLevel; +import org.apache.maven.api.logging.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.spi.LoggingEventBuilder; + +import static java.util.Objects.requireNonNull; + +/** + * Default {@link Logger} implementation backed by an SLF4J {@link org.slf4j.Logger}. + */ +public class DefaultLogger implements Logger { + private static final LogEventBuilder NOP_BUILDER = new NopLogEventBuilder(); + + private final org.slf4j.Logger logger; + + public DefaultLogger(org.slf4j.Logger logger) { + this.logger = requireNonNull(logger, "logger cannot be null"); + } + + @Override + @Nonnull + public String name() { + return logger.getName(); + } + + @Override + public boolean isEnabled(@Nonnull LogLevel level) { + requireNonNull(level, "level cannot be null"); + return switch (level) { + case TRACE -> logger.isTraceEnabled(); + case DEBUG -> logger.isDebugEnabled(); + case INFO -> logger.isInfoEnabled(); + case WARN -> logger.isWarnEnabled(); + case ERROR -> logger.isErrorEnabled(); + }; + } + + @Override + @Nonnull + public LogEventBuilder atTrace() { + return at(LogLevel.TRACE); + } + + @Override + @Nonnull + public LogEventBuilder atDebug() { + return at(LogLevel.DEBUG); + } + + @Override + @Nonnull + public LogEventBuilder atInfo() { + return at(LogLevel.INFO); + } + + @Override + @Nonnull + public LogEventBuilder atWarn() { + return at(LogLevel.WARN); + } + + @Override + @Nonnull + public LogEventBuilder atError() { + return at(LogLevel.ERROR); + } + + @Override + @Nonnull + public LogEventBuilder at(@Nonnull LogLevel level) { + if (!isEnabled(level)) { + return NOP_BUILDER; + } + return new DefaultLogEventBuilder(logger, level); + } + + @Override + @Nonnull + public Logger child(@Nonnull String name) { + requireNonNull(name, "name cannot be null"); + if (name.isEmpty()) { + throw new IllegalArgumentException("child logger name cannot be empty"); + } + String parentName = logger.getName(); + String childName = parentName.isEmpty() ? name : parentName + "." + name; + return new DefaultLogger(LoggerFactory.getLogger(childName)); + } + + private static final class NopLogEventBuilder implements LogEventBuilder { + @Override + @Nonnull + public LogEventBuilder withKeyValue(@Nonnull String key, String value) { + return this; + } + + @Override + @Nonnull + public LogEventBuilder withKeyValue(@Nonnull String key, long value) { + return this; + } + + @Override + @Nonnull + public LogEventBuilder withKeyValue(@Nonnull String key, boolean value) { + return this; + } + + @Override + @Nonnull + public LogEventBuilder withThrowable(Throwable t) { + return this; + } + + @Override + @Nonnull + public LogEventBuilder withProjectId(String projectId) { + return this; + } + + @Override + @Nonnull + public LogEventBuilder withMojoId(String mojoId) { + return this; + } + + @Override + public void log(@Nonnull String message) {} + + @Override + public void log(@Nonnull String format, Object arg) {} + + @Override + public void log(@Nonnull String format, Object arg1, Object arg2) {} + + @Override + public void log(@Nonnull String format, Object... args) {} + + @Override + public void log(@Nonnull Supplier<String> messageSupplier) {} + } + + private static final class DefaultLogEventBuilder implements LogEventBuilder { + private final org.slf4j.Logger logger; + private final LogLevel level; + private Throwable throwable; + private LoggingEventBuilder slf4jBuilder; + + DefaultLogEventBuilder(org.slf4j.Logger logger, LogLevel level) { + this.logger = logger; + this.level = level; + } + + private LoggingEventBuilder ensureBuilder() { + if (slf4jBuilder == null) { + slf4jBuilder = switch (level) { + case TRACE -> logger.atTrace(); + case DEBUG -> logger.atDebug(); + case INFO -> logger.atInfo(); + case WARN -> logger.atWarn(); + case ERROR -> logger.atError(); + }; + if (throwable != null) { + slf4jBuilder.setCause(throwable); + } + } + return slf4jBuilder; + } + + @Override + @Nonnull + public LogEventBuilder withKeyValue(@Nonnull String key, String value) { + ensureBuilder().addKeyValue(key, value); + return this; + } + + @Override + @Nonnull + public LogEventBuilder withKeyValue(@Nonnull String key, long value) { + ensureBuilder().addKeyValue(key, value); + return this; + } + + @Override + @Nonnull + public LogEventBuilder withKeyValue(@Nonnull String key, boolean value) { + ensureBuilder().addKeyValue(key, value); + return this; + } + + @Override + @Nonnull + public LogEventBuilder withThrowable(Throwable t) { + if (slf4jBuilder != null) { + slf4jBuilder.setCause(t); + } else { + this.throwable = t; + } + return this; + } + + @Override + @Nonnull + public LogEventBuilder withProjectId(String projectId) { + return this; + } + + @Override + @Nonnull + public LogEventBuilder withMojoId(String mojoId) { + return this; + } + + @Override + public void log(@Nonnull String message) { + if (slf4jBuilder != null) { + slf4jBuilder.log(message); + return; + } + if (throwable != null) { + switch (level) { + case TRACE -> logger.trace(message, throwable); + case DEBUG -> logger.debug(message, throwable); + case INFO -> logger.info(message, throwable); + case WARN -> logger.warn(message, throwable); + case ERROR -> logger.error(message, throwable); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } else { + switch (level) { + case TRACE -> logger.trace(message); + case DEBUG -> logger.debug(message); + case INFO -> logger.info(message); + case WARN -> logger.warn(message); + case ERROR -> logger.error(message); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } + } + + @Override + public void log(@Nonnull String format, Object arg) { + if (slf4jBuilder != null) { + slf4jBuilder.log(format, arg); + return; + } + if (throwable != null) { + switch (level) { + case TRACE -> logger.trace(format, arg, throwable); + case DEBUG -> logger.debug(format, arg, throwable); + case INFO -> logger.info(format, arg, throwable); + case WARN -> logger.warn(format, arg, throwable); + case ERROR -> logger.error(format, arg, throwable); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } else { + switch (level) { + case TRACE -> logger.trace(format, arg); + case DEBUG -> logger.debug(format, arg); + case INFO -> logger.info(format, arg); + case WARN -> logger.warn(format, arg); + case ERROR -> logger.error(format, arg); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } + } + + @Override + public void log(@Nonnull String format, Object arg1, Object arg2) { + if (slf4jBuilder != null) { + slf4jBuilder.log(format, arg1, arg2); + return; + } + if (throwable != null) { + switch (level) { + case TRACE -> logger.trace(format, arg1, arg2, throwable); + case DEBUG -> logger.debug(format, arg1, arg2, throwable); + case INFO -> logger.info(format, arg1, arg2, throwable); + case WARN -> logger.warn(format, arg1, arg2, throwable); + case ERROR -> logger.error(format, arg1, arg2, throwable); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } else { + switch (level) { + case TRACE -> logger.trace(format, arg1, arg2); + case DEBUG -> logger.debug(format, arg1, arg2); + case INFO -> logger.info(format, arg1, arg2); + case WARN -> logger.warn(format, arg1, arg2); + case ERROR -> logger.error(format, arg1, arg2); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } + } + + @Override + public void log(@Nonnull String format, Object... args) { + if (slf4jBuilder != null) { + slf4jBuilder.log(format, args); + return; + } + if (throwable != null) { + Object[] withThrowable = new Object[args.length + 1]; + System.arraycopy(args, 0, withThrowable, 0, args.length); + withThrowable[args.length] = throwable; + switch (level) { + case TRACE -> logger.trace(format, withThrowable); + case DEBUG -> logger.debug(format, withThrowable); + case INFO -> logger.info(format, withThrowable); + case WARN -> logger.warn(format, withThrowable); + case ERROR -> logger.error(format, withThrowable); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } else { + switch (level) { + case TRACE -> logger.trace(format, args); + case DEBUG -> logger.debug(format, args); + case INFO -> logger.info(format, args); + case WARN -> logger.warn(format, args); + case ERROR -> logger.error(format, args); + default -> throw new IllegalStateException("Unexpected level: " + level); + } + } + } + + @Override + public void log(@Nonnull Supplier<String> messageSupplier) { + requireNonNull(messageSupplier, "messageSupplier cannot be null"); + log(messageSupplier.get()); + } + } +} diff --git a/impl/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java b/impl/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java index 476f2aadcd..8188efa9e8 100644 --- a/impl/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java +++ b/impl/maven-core/src/main/java/org/apache/maven/plugin/DefaultBuildPluginManager.java @@ -35,7 +35,7 @@ import org.apache.maven.execution.MojoExecutionEvent; import org.apache.maven.execution.MojoExecutionListener; import org.apache.maven.execution.scope.internal.MojoExecutionScope; -import org.apache.maven.internal.impl.DefaultLog; +import org.apache.maven.internal.impl.DefaultLogger; import org.apache.maven.internal.impl.DefaultMojoExecution; import org.apache.maven.internal.impl.InternalMavenSession; import org.apache.maven.model.Plugin; @@ -123,8 +123,8 @@ public void executeMojo(MavenSession session, MojoExecution mojoExecution) scope.seed(MavenProject.class, project); scope.seed(MojoExecution.class, mojoExecution); scope.seed( - org.apache.maven.api.plugin.Log.class, - new DefaultLog(LoggerFactory.getLogger( + org.apache.maven.api.logging.Logger.class, + new DefaultLogger(LoggerFactory.getLogger( mojoExecution.getMojoDescriptor().getImplementation()))); InternalMavenSession sessionV4 = InternalMavenSession.from(session.getSession()); scope.seed(Project.class, sessionV4.getProject(project)); diff --git a/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java b/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java index d881c31b38..8ee04643e7 100644 --- a/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java +++ b/impl/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultMavenPluginManager.java @@ -67,7 +67,7 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.scope.internal.MojoExecutionScope; import org.apache.maven.execution.scope.internal.MojoExecutionScopeModule; -import org.apache.maven.internal.impl.DefaultLog; +import org.apache.maven.internal.impl.DefaultLogger; import org.apache.maven.internal.impl.DefaultMojoExecution; import org.apache.maven.internal.impl.InternalMavenSession; import org.apache.maven.internal.impl.SisuDiBridgeModule; @@ -563,7 +563,7 @@ private <T> T loadV4Mojo( Project project = sessionV4.getProject(session.getCurrentProject()); org.apache.maven.api.MojoExecution execution = new DefaultMojoExecution(sessionV4, mojoExecution); - org.apache.maven.api.plugin.Log log = new DefaultLog( + org.apache.maven.api.logging.Logger log = new DefaultLogger( LoggerFactory.getLogger(mojoExecution.getMojoDescriptor().getImplementation())); try { Injector injector = Injector.create(); @@ -573,7 +573,7 @@ private <T> T loadV4Mojo( injector.bindInstance(Session.class, sessionV4); injector.bindInstance(Project.class, project); injector.bindInstance(org.apache.maven.api.MojoExecution.class, execution); - injector.bindInstance(org.apache.maven.api.plugin.Log.class, log); + injector.bindInstance(org.apache.maven.api.logging.Logger.class, log); Map<Class<? extends Service>, Supplier<? extends Service>> services = sessionV4.getAllServices(); services.forEach((itf, svc) -> injector.bindSupplier((Class<Service>) itf, (Supplier<Service>) svc)); diff --git a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java deleted file mode 100644 index eb290734fb..0000000000 --- a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLogTest.java +++ /dev/null @@ -1,196 +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.internal.impl; - -import org.apache.maven.api.plugin.Log; -import org.junit.jupiter.api.Test; -import org.slf4j.Logger; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotSame; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -/** - * Tests for {@link DefaultLog}. - */ -class DefaultLogTest { - - /** - * Regression test: {@code warn(Supplier, Throwable)} was incorrectly - * calling {@code logger.info()} instead of {@code logger.warn()}. - */ - @Test - void warnWithSupplierAndThrowableDelegatesToWarn() { - Logger mockLogger = mock(Logger.class); - when(mockLogger.isWarnEnabled()).thenReturn(true); - - DefaultLog log = new DefaultLog(mockLogger); - RuntimeException ex = new RuntimeException("test"); - log.warn(() -> "warning message", ex); - - verify(mockLogger).warn("warning message", ex); - } - - /** - * Verify trace methods delegate to the SLF4J logger correctly. - */ - @Test - void traceMethodsDelegateToSlf4jTrace() { - Logger mockLogger = mock(Logger.class); - when(mockLogger.isTraceEnabled()).thenReturn(true); - - DefaultLog log = new DefaultLog(mockLogger); - log.trace("trace message"); - - verify(mockLogger).trace("trace message"); - } - - /** - * Verify that trace methods are no-ops when trace is disabled. - */ - @Test - void traceIsNoOpWhenDisabled() { - Logger mockLogger = mock(Logger.class); - when(mockLogger.isTraceEnabled()).thenReturn(false); - - DefaultLog log = new DefaultLog(mockLogger); - log.trace("should not be logged"); - - verify(mockLogger).isTraceEnabled(); - verifyNoMoreInteractions(mockLogger); - } - - /** - * Verify that {@code child()} creates a new logger with the - * expected hierarchical name. - */ - @Test - void childCreatesSubLogger() { - Logger mockLogger = mock(Logger.class); - when(mockLogger.getName()).thenReturn("org.apache.maven.plugins.compiler.CompilerMojo"); - - DefaultLog parent = new DefaultLog(mockLogger); - Log child = parent.child("diagnostics"); - - assertNotSame(parent, child); - assertTrue(child instanceof DefaultLog, "child should be a DefaultLog"); - } - - /** - * Verify that the default {@code Log.isTraceEnabled()} returns false, - * preventing {@code AbstractMethodError} for third-party implementors. - */ - @Test - void defaultTraceIsDisabled() { - // Use a minimal Log implementation that relies on defaults - Log minimal = new Log() { - @Override - public boolean isDebugEnabled() { - return false; - } - - @Override - public void debug(CharSequence c) {} - - @Override - public void debug(CharSequence c, Throwable e) {} - - @Override - public void debug(Throwable e) {} - - @Override - public void debug(java.util.function.Supplier<String> c) {} - - @Override - public void debug(java.util.function.Supplier<String> c, Throwable e) {} - - @Override - public boolean isInfoEnabled() { - return false; - } - - @Override - public void info(CharSequence c) {} - - @Override - public void info(CharSequence c, Throwable e) {} - - @Override - public void info(Throwable e) {} - - @Override - public void info(java.util.function.Supplier<String> c) {} - - @Override - public void info(java.util.function.Supplier<String> c, Throwable e) {} - - @Override - public boolean isWarnEnabled() { - return false; - } - - @Override - public void warn(CharSequence c) {} - - @Override - public void warn(CharSequence c, Throwable e) {} - - @Override - public void warn(Throwable e) {} - - @Override - public void warn(java.util.function.Supplier<String> c) {} - - @Override - public void warn(java.util.function.Supplier<String> c, Throwable e) {} - - @Override - public boolean isErrorEnabled() { - return false; - } - - @Override - public void error(CharSequence c) {} - - @Override - public void error(CharSequence c, Throwable e) {} - - @Override - public void error(Throwable e) {} - - @Override - public void error(java.util.function.Supplier<String> c) {} - - @Override - public void error(java.util.function.Supplier<String> c, Throwable e) {} - }; - - // These should NOT throw AbstractMethodError — they use defaults - assertEquals(false, minimal.isTraceEnabled()); - minimal.trace("should be a no-op"); - minimal.trace("no-op", new RuntimeException()); - minimal.trace(new RuntimeException()); - minimal.trace(() -> "no-op"); - minimal.trace(() -> "no-op", new RuntimeException()); - } -} diff --git a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLoggerTest.java b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLoggerTest.java new file mode 100644 index 0000000000..a2066391e0 --- /dev/null +++ b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLoggerTest.java @@ -0,0 +1,91 @@ +/* + * 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.impl; + +import org.apache.maven.api.logging.Logger; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Tests for {@link DefaultLogger}. + */ +class DefaultLoggerTest { + + @Test + void warnWithSupplierAndThrowableDelegatesToWarn() { + org.slf4j.Logger mockLogger = mock(org.slf4j.Logger.class); + when(mockLogger.isWarnEnabled()).thenReturn(true); + + Logger log = new DefaultLogger(mockLogger); + RuntimeException ex = new RuntimeException("test"); + log.warn(() -> "warning message", ex); + + verify(mockLogger).warn("warning message", ex); + } + + @Test + void traceMethodsDelegateToSlf4jTrace() { + org.slf4j.Logger mockLogger = mock(org.slf4j.Logger.class); + when(mockLogger.isTraceEnabled()).thenReturn(true); + + Logger log = new DefaultLogger(mockLogger); + log.trace("trace message"); + + verify(mockLogger).trace("trace message"); + } + + @Test + void traceIsNoOpWhenDisabled() { + org.slf4j.Logger mockLogger = mock(org.slf4j.Logger.class); + when(mockLogger.isTraceEnabled()).thenReturn(false); + + Logger log = new DefaultLogger(mockLogger); + log.trace("should not be logged"); + + verify(mockLogger).isTraceEnabled(); + verifyNoMoreInteractions(mockLogger); + } + + @Test + void childCreatesChildLoggerWithAppendedName() { + org.slf4j.Logger mockLogger = mock(org.slf4j.Logger.class); + when(mockLogger.getName()).thenReturn("org.example.MyMojo"); + + Logger log = new DefaultLogger(mockLogger); + Logger child = log.child("sub"); + + assertNotSame(log, child); + assertEquals("org.example.MyMojo.sub", child.name()); + } + + @Test + void childRejectsEmptyName() { + org.slf4j.Logger mockLogger = mock(org.slf4j.Logger.class); + Logger log = new DefaultLogger(mockLogger); + + assertThrows(IllegalArgumentException.class, () -> log.child("")); + } +} diff --git a/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/MojoExtension.java b/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/MojoExtension.java index fb5a804088..81eaeac211 100644 --- a/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/MojoExtension.java +++ b/impl/maven-testing/src/main/java/org/apache/maven/testing/plugin/MojoExtension.java @@ -51,7 +51,7 @@ import org.apache.maven.api.model.ConfigurationContainer; import org.apache.maven.api.model.Model; import org.apache.maven.api.model.Source; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.Mojo; import org.apache.maven.api.plugin.descriptor.MojoDescriptor; import org.apache.maven.api.plugin.descriptor.Parameter; @@ -78,7 +78,7 @@ import org.apache.maven.impl.model.DefaultInterpolator; import org.apache.maven.impl.model.DefaultModelPathTranslator; import org.apache.maven.impl.model.DefaultPathTranslator; -import org.apache.maven.internal.impl.DefaultLog; +import org.apache.maven.internal.impl.DefaultLogger; import org.apache.maven.internal.xml.XmlPlexusConfiguration; import org.apache.maven.lifecycle.internal.MojoDescriptorCreator; import org.apache.maven.model.v4.MavenMerger; @@ -340,7 +340,7 @@ public void beforeEach(ExtensionContext context) throws Exception { /* binder.install(ProviderMethodsModule.forObject(context.getRequiredTestInstance())); binder.requestInjection(context.getRequiredTestInstance()); - binder.bind(Log.class).toInstance(new DefaultLog(LoggerFactory.getLogger("anonymous"))); + binder.bind(Logger.class).toInstance(new DefaultLogger(LoggerFactory.getLogger("anonymous"))); binder.bind(ExtensionContext.class).toInstance(context); // Load maven 4 api Services interfaces and try to bind them to the (possible) mock instances // returned by the (possibly) mock InternalSession @@ -534,8 +534,8 @@ MojoExecution createMojoExecution() { @Provides @Singleton @Priority(-10) - Log createLog() { - return new DefaultLog(LoggerFactory.getLogger("anonymous")); + Logger createLog() { + return new DefaultLogger(LoggerFactory.getLogger("anonymous")); } @Provides diff --git a/its/core-it-suite/src/test/resources/gh-11055-di-service-injection/src/main/java/com/gitlab/tkslaw/ditests/DITestsMojoBase.java b/its/core-it-suite/src/test/resources/gh-11055-di-service-injection/src/main/java/com/gitlab/tkslaw/ditests/DITestsMojoBase.java index 813d18ddfd..c9ada74e3f 100644 --- a/its/core-it-suite/src/test/resources/gh-11055-di-service-injection/src/main/java/com/gitlab/tkslaw/ditests/DITestsMojoBase.java +++ b/its/core-it-suite/src/test/resources/gh-11055-di-service-injection/src/main/java/com/gitlab/tkslaw/ditests/DITestsMojoBase.java @@ -21,12 +21,12 @@ import org.apache.maven.api.Project; import org.apache.maven.api.Session; import org.apache.maven.api.di.Inject; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.Mojo; public class DITestsMojoBase implements Mojo { @Inject - protected Log log; + protected Logger log; @Inject protected Session session; diff --git a/its/core-it-suite/src/test/resources/gh-11378-sealed-parameter-config/plugin/src/main/java/org/apache/maven/its/gh11378/TestMojo.java b/its/core-it-suite/src/test/resources/gh-11378-sealed-parameter-config/plugin/src/main/java/org/apache/maven/its/gh11378/TestMojo.java index 168707733f..80fa9c5ba4 100644 --- a/its/core-it-suite/src/test/resources/gh-11378-sealed-parameter-config/plugin/src/main/java/org/apache/maven/its/gh11378/TestMojo.java +++ b/its/core-it-suite/src/test/resources/gh-11378-sealed-parameter-config/plugin/src/main/java/org/apache/maven/its/gh11378/TestMojo.java @@ -19,7 +19,7 @@ package org.apache.maven.its.gh11378; import org.apache.maven.api.di.Inject; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.annotations.Mojo; import org.apache.maven.api.plugin.annotations.Parameter; @@ -27,7 +27,7 @@ public class TestMojo implements org.apache.maven.api.plugin.Mojo { @Inject - private Log log; + private Logger log; @Parameter private Artifact artifact; diff --git a/its/core-it-suite/src/test/resources/mng-1088/plugin/src/main/java/org/apache/maven/plugin/coreit/TouchMojo.java b/its/core-it-suite/src/test/resources/mng-1088/plugin/src/main/java/org/apache/maven/plugin/coreit/TouchMojo.java index 57b887dc3a..6cd28add57 100644 --- a/its/core-it-suite/src/test/resources/mng-1088/plugin/src/main/java/org/apache/maven/plugin/coreit/TouchMojo.java +++ b/its/core-it-suite/src/test/resources/mng-1088/plugin/src/main/java/org/apache/maven/plugin/coreit/TouchMojo.java @@ -24,7 +24,7 @@ import org.apache.maven.api.Project; import org.apache.maven.api.di.Inject; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.MojoException; import org.apache.maven.api.plugin.annotations.Mojo; import org.apache.maven.api.plugin.annotations.Parameter; @@ -41,7 +41,7 @@ public class TouchMojo implements org.apache.maven.api.plugin.Mojo { @Inject - private Log log; + private Logger log; @Inject private Project project; diff --git a/its/core-it-suite/src/test/resources/mng-12534-after-annotation/plugin/src/main/java/org/apache/maven/its/mng12534/TouchMojo.java b/its/core-it-suite/src/test/resources/mng-12534-after-annotation/plugin/src/main/java/org/apache/maven/its/mng12534/TouchMojo.java index 01ac60c4ef..9ed399e4c9 100644 --- a/its/core-it-suite/src/test/resources/mng-12534-after-annotation/plugin/src/main/java/org/apache/maven/its/mng12534/TouchMojo.java +++ b/its/core-it-suite/src/test/resources/mng-12534-after-annotation/plugin/src/main/java/org/apache/maven/its/mng12534/TouchMojo.java @@ -24,7 +24,7 @@ import org.apache.maven.api.Project; import org.apache.maven.api.di.Inject; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.annotations.After; import org.apache.maven.api.plugin.annotations.Mojo; @@ -45,7 +45,7 @@ public class TouchMojo implements org.apache.maven.api.plugin.Mojo { @Inject - private Log log; + private Logger log; @Inject private Project project; diff --git a/its/core-it-suite/src/test/resources/mng-8525-maven-di-plugin/src/main/java/org/apache/maven/plugins/HelloMojo.java b/its/core-it-suite/src/test/resources/mng-8525-maven-di-plugin/src/main/java/org/apache/maven/plugins/HelloMojo.java index ed9610735e..24fa1ecd40 100644 --- a/its/core-it-suite/src/test/resources/mng-8525-maven-di-plugin/src/main/java/org/apache/maven/plugins/HelloMojo.java +++ b/its/core-it-suite/src/test/resources/mng-8525-maven-di-plugin/src/main/java/org/apache/maven/plugins/HelloMojo.java @@ -20,7 +20,7 @@ import org.apache.maven.api.Lifecycle.Phase; import org.apache.maven.api.di.Inject; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.annotations.Mojo; import org.apache.maven.api.plugin.annotations.Parameter; @@ -31,7 +31,7 @@ public class HelloMojo implements org.apache.maven.api.plugin.Mojo { private MavenDIComponent component; @Inject - private Log logger; + private Logger logger; @Parameter(property = "name") private String name; diff --git a/its/core-it-suite/src/test/resources/mng-8572-di-type-handler/extension/src/main/java/org/apache/maven/its/mng8572/extension/NoOpMojo.java b/its/core-it-suite/src/test/resources/mng-8572-di-type-handler/extension/src/main/java/org/apache/maven/its/mng8572/extension/NoOpMojo.java index fa08a3ba0c..eaafefea70 100644 --- a/its/core-it-suite/src/test/resources/mng-8572-di-type-handler/extension/src/main/java/org/apache/maven/its/mng8572/extension/NoOpMojo.java +++ b/its/core-it-suite/src/test/resources/mng-8572-di-type-handler/extension/src/main/java/org/apache/maven/its/mng8572/extension/NoOpMojo.java @@ -19,7 +19,7 @@ package org.apache.maven.its.mng8572.extension; import org.apache.maven.api.di.Inject; -import org.apache.maven.api.plugin.Log; +import org.apache.maven.api.logging.Logger; import org.apache.maven.api.plugin.Mojo; import org.apache.maven.api.plugin.annotations.Parameter; @@ -33,7 +33,7 @@ public class NoOpMojo implements Mojo { @Inject - private Log log; + private Logger log; @Parameter(defaultValue = "${project.name}", readonly = true) private String projectName; diff --git a/pom.xml b/pom.xml index 2630f30c28..c7565803d0 100644 --- a/pom.xml +++ b/pom.xml @@ -269,6 +269,11 @@ under the License. <artifactId>maven-api-plugin</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.apache.maven</groupId> + <artifactId>maven-api-log</artifactId> + <version>${project.version}</version> + </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-api-xml</artifactId>
