This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new ce22a13b5779 CAMEL-26937: camel-jbang - the short commands start 
without log4j, and print without a JLine terminal when piped (#30016)
ce22a13b5779 is described below

commit ce22a13b5779c52486cf4aba90ae3f13ce8ff83c
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 15 16:35:41 2026 +0100

    CAMEL-26937: camel-jbang - the short commands start without log4j, and 
print without a JLine terminal when piped (#30016)
    
    - The CLI has an SLF4J provider of its own (CliLoggerProvider, installed by 
the main method of the launcher and of
      JBang): its loggers log nothing until the CLI configures the logging 
(RuntimeUtil.configureLog, camel infra run),
      and then log with log4j. A command that turns the logging off, such as 
camel ps, get or doc, no longer starts log4j
      only because a class of Camel creates a static logger. Log4j already 
logged nothing until the CLI configured it
      (CAMEL-26429), so the commands log as before.
    - Without a terminal a command leaves out the ANSI colors of printColored 
itself, as the console would, instead of
      asking the console, which builds a JLine system terminal to find that 
out. -Djansi.mode still goes to the console.
    
    Measured with the launcher on JDK 25, warm CDS, best of 7: camel ps 237 -> 
140 ms, get route 259 -> 170 ms,
    doc timer 245 -> 150 ms, camel log (piped) 439 -> 347 ms. The debug log of 
camel run is the same, line for line.
    
    CAMEL-26937: camel-jbang - the Javadoc of stripsColorsItself in shorter 
sentences (review)
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../dsl/jbang/core/commands/CamelCommand.java      |  31 ++-
 .../dsl/jbang/core/commands/CamelJBangMain.java    |   6 +
 .../dsl/jbang/core/commands/infra/InfraRun.java    |   2 +
 .../core/commands/CamelCommandColorsTest.java      |  77 ++++++++
 .../dsl/jbang/run/common/CliLoggerProvider.java    | 218 +++++++++++++++++++++
 .../camel/dsl/jbang/run/common/CliLogging.java     |  93 +++++++++
 .../camel/dsl/jbang/run/common/RuntimeUtil.java    |   8 +-
 .../jbang/run/common/CliLoggerProviderTest.java    | 119 +++++++++++
 .../camel/dsl/jbang/run/common/CliLoggingTest.java |  83 ++++++++
 .../camel/dsl/jbang/launcher/CamelLauncher.java    |   4 +
 .../jbang/launcher/LauncherStartupLoggingTest.java |  11 ++
 11 files changed, 647 insertions(+), 5 deletions(-)

diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
index b504f74fcd17..3cfb3e83838c 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelCommand.java
@@ -23,6 +23,7 @@ import java.util.List;
 import java.util.Optional;
 import java.util.Properties;
 import java.util.Set;
+import java.util.regex.Pattern;
 
 import org.aesh.command.Command;
 import org.aesh.command.CommandResult;
@@ -46,6 +47,9 @@ import org.jline.jansi.AnsiMode;
 
 public abstract class CamelCommand implements Command<CommandInvocation>, 
CommandTree.ParsedCommandAware {
 
+    // an ANSI escape code (CSI), such as the colors of the Jansi Ansi builder
+    private static final Pattern ANSI_CODE = 
Pattern.compile("\\x1B\\[[0-9;:?]*[ -/]*[@-~]");
+
     // the model of the options of this command, and the tree it runs in (set 
when the command line is built)
     private ProcessedCommand<?, ?> processedCommand;
     private CommandTree tree;
@@ -327,7 +331,9 @@ public abstract class CamelCommand implements 
Command<CommandInvocation>, Comman
      * CLI that runs the command in its own JVM and keeps its output (see 
{@link CliRunner}).
      */
     protected void printColored(Object text) {
-        if (printsToConsole()) {
+        if (printsToConsole() && stripsColorsItself()) {
+            printer().print(withoutColors(text));
+        } else if (printsToConsole()) {
             AnsiConsole.out().print(text);
         } else {
             printer().print(String.valueOf(text));
@@ -338,7 +344,9 @@ public abstract class CamelCommand implements 
Command<CommandInvocation>, Comman
      * Prints a line with colors (ANSI escape codes), see {@link 
#printColored(Object)}.
      */
     protected void printlnColored(Object text) {
-        if (printsToConsole()) {
+        if (printsToConsole() && stripsColorsItself()) {
+            printer().println(withoutColors(text));
+        } else if (printsToConsole()) {
             AnsiConsole.out().println(text);
         } else {
             printer().println(String.valueOf(text));
@@ -352,7 +360,24 @@ public abstract class CamelCommand implements 
Command<CommandInvocation>, Comman
      * (CAMEL-26911).
      */
     protected boolean colorsStripped() {
-        return printsToConsole() && AnsiConsole.out().getMode() == 
AnsiMode.Strip;
+        return printsToConsole() && (stripsColorsItself() || 
AnsiConsole.out().getMode() == AnsiMode.Strip);
+    }
+
+    /**
+     * Whether the command leaves out the colors itself, instead of the 
console. When the output is not a terminal, the
+     * console would leave them out too, but finding that out builds a JLine 
terminal, which costs more than most
+     * commands take to print (CAMEL-26937). Not when the console is told how 
to print the colors
+     * ({@code -Djansi.mode}).
+     */
+    private static boolean stripsColorsItself() {
+        return !EnvironmentHelper.hasTerminal()
+                && System.getProperty(AnsiConsole.JANSI_MODE) == null
+                && System.getProperty(AnsiConsole.JANSI_OUT_MODE) == null;
+    }
+
+    // the text without the ANSI escape codes of its colors
+    private static String withoutColors(Object text) {
+        return ANSI_CODE.matcher(String.valueOf(text)).replaceAll("");
     }
 
     /**
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
index 16b1e577be84..4293e0b23a0d 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/CamelJBangMain.java
@@ -80,6 +80,7 @@ import org.apache.camel.dsl.jbang.core.common.JsonOutput;
 import org.apache.camel.dsl.jbang.core.common.Plugin;
 import org.apache.camel.dsl.jbang.core.common.PluginHelper;
 import org.apache.camel.dsl.jbang.core.common.PluginType;
+import org.apache.camel.dsl.jbang.run.common.CliLogging;
 import org.apache.camel.dsl.jbang.run.common.Printer;
 import org.apache.camel.util.json.JsonObject;
 
@@ -110,7 +111,12 @@ public class CamelJBangMain implements 
Command<CommandInvocation> {
     // the plugins whose commands were added, to add them to a new command 
line too
     private final List<Plugin> plugins = new CopyOnWriteArrayList<>();
 
+    /**
+     * The main method of the CLI that JBang runs 
(camel-jbang-main/dist/CamelJBang.java).
+     */
     public static void run(String... args) {
+        // before anything creates a logger
+        CliLogging.install();
         run(new CamelJBangMain(), args);
     }
 
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
index a4c9514399ad..1041c8c6bb6f 100644
--- 
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
@@ -41,6 +41,7 @@ import org.apache.camel.dsl.jbang.core.common.CliException;
 import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
 import org.apache.camel.dsl.jbang.core.common.EnvironmentHelper;
 import org.apache.camel.dsl.jbang.core.common.JsonOutput;
+import org.apache.camel.dsl.jbang.run.common.CliLogging;
 import org.apache.camel.dsl.jbang.run.common.Printer;
 import org.apache.camel.dsl.jbang.run.common.RuntimeUtil;
 import org.apache.camel.main.download.DependencyDownloaderClassLoader;
@@ -253,6 +254,7 @@ public class InfraRun extends InfraBaseCommand {
             URL logConfig = 
InfraRun.class.getClassLoader().getResource("log4j2-infra.properties");
             if (logConfig != null) {
                 Configurator.reconfigure(logConfig.toURI());
+                CliLogging.loggingConfigured();
             }
             String prefix = "";
             if (testServiceImplementation != null) {
diff --git 
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/CamelCommandColorsTest.java
 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/CamelCommandColorsTest.java
new file mode 100644
index 000000000000..20b9f1e74e00
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/CamelCommandColorsTest.java
@@ -0,0 +1,77 @@
+/*
+ * 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.camel.dsl.jbang.core.commands;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.camel.dsl.jbang.core.common.EnvironmentHelper;
+import org.jline.jansi.Ansi;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+/**
+ * Without a terminal, a command prints its colored text without the colors 
itself, as the console would, without
+ * building the JLine terminal that the console needs to find that out 
(CAMEL-26937).
+ */
+class CamelCommandColorsTest {
+
+    @Test
+    void coloredTextWithoutTerminalIsPrintedWithoutColors() throws Exception {
+        assumeFalse(EnvironmentHelper.hasTerminal(), "runs without a 
terminal");
+
+        String out = printToConsole(new ColoredCommand(new CamelJBangMain()));
+
+        assertThat(out).isEqualTo("red and bold" + System.lineSeparator() + 
"plain");
+    }
+
+    @Test
+    void consoleStripsTheColorsWithoutTerminal() {
+        assumeFalse(EnvironmentHelper.hasTerminal(), "runs without a 
terminal");
+
+        assertThat(new ColoredCommand(new 
CamelJBangMain()).colorsStripped()).isTrue();
+    }
+
+    private static String printToConsole(CamelCommand command) throws 
Exception {
+        PrintStream previous = System.out;
+        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+        System.setOut(new PrintStream(bytes, true, StandardCharsets.UTF_8));
+        try {
+            command.doCall();
+        } finally {
+            System.setOut(previous);
+        }
+        return bytes.toString(StandardCharsets.UTF_8);
+    }
+
+    private static final class ColoredCommand extends CamelCommand {
+
+        ColoredCommand(CamelJBangMain main) {
+            super(main);
+        }
+
+        @Override
+        public Integer doCall() {
+            printlnColored(Ansi.ansi().fgRed().a("red").reset().a(" and 
").bold().a("bold").reset());
+            printColored(Ansi.ansi().a("plain"));
+            return 0;
+        }
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/CliLoggerProvider.java
 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/CliLoggerProvider.java
new file mode 100644
index 000000000000..1f0bb1b5c532
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/CliLoggerProvider.java
@@ -0,0 +1,218 @@
+/*
+ * 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.camel.dsl.jbang.run.common;
+
+import java.util.Deque;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Supplier;
+
+import org.slf4j.ILoggerFactory;
+import org.slf4j.IMarkerFactory;
+import org.slf4j.Logger;
+import org.slf4j.helpers.NOP_FallbackServiceProvider;
+import org.slf4j.helpers.SubstituteLogger;
+import org.slf4j.spi.MDCAdapter;
+import org.slf4j.spi.SLF4JServiceProvider;
+
+/**
+ * The SLF4J provider of a Camel CLI started from the command line: its 
loggers log nothing until the CLI configures the
+ * logging ({@link RuntimeUtil#configureLog}), and then log with the SLF4J 
provider on the classpath (log4j).
+ * <p/>
+ * Most commands, such as camel ps or camel get, turn the logging off, and 
something that only creates a logger (a
+ * static logger of a class of Camel) then made log4j start, which is about a 
third of such a command (CAMEL-26937).
+ * Log4j already logged nothing until the CLI configured it (CAMEL-26429), so 
the commands log as before. The main
+ * method of the CLI installs it, see {@link CliLogging#install()}.
+ */
+public final class CliLoggerProvider implements SLF4JServiceProvider {
+
+    private final CliLoggerFactory loggerFactory = new CliLoggerFactory();
+    private final MDCAdapter mdcAdapter = new CliMDCAdapter(this);
+    private final Supplier<SLF4JServiceProvider> delegateFinder;
+    private volatile SLF4JServiceProvider delegate;
+
+    /**
+     * The provider that SLF4J creates, as the system property {@code 
slf4j.provider} names it.
+     */
+    public CliLoggerProvider() {
+        this(CliLoggerProvider::findProvider);
+    }
+
+    CliLoggerProvider(Supplier<SLF4JServiceProvider> delegateFinder) {
+        this.delegateFinder = delegateFinder;
+    }
+
+    /**
+     * The CLI configured the logging: from now on the loggers log with the 
provider on the classpath.
+     */
+    void configured() {
+        loggerFactory.delegateTo(delegate().getLoggerFactory());
+    }
+
+    @Override
+    public void initialize() {
+        // SLF4J chose this provider, as something asked for a logger
+        CliLogging.bound(this::configured);
+    }
+
+    @Override
+    public ILoggerFactory getLoggerFactory() {
+        return loggerFactory;
+    }
+
+    @Override
+    public IMarkerFactory getMarkerFactory() {
+        return delegate().getMarkerFactory();
+    }
+
+    @Override
+    public MDCAdapter getMDCAdapter() {
+        // SLF4J asks for it when it chooses the provider, before anything logs
+        return mdcAdapter;
+    }
+
+    @Override
+    public String getRequestedApiVersion() {
+        return "2.0.99";
+    }
+
+    // the provider on the classpath, which is found as SLF4J would without 
this one
+    private SLF4JServiceProvider delegate() {
+        SLF4JServiceProvider answer = delegate;
+        if (answer == null) {
+            synchronized (this) {
+                answer = delegate;
+                if (answer == null) {
+                    answer = delegateFinder.get();
+                    answer.initialize();
+                    delegate = answer;
+                }
+            }
+        }
+        return answer;
+    }
+
+    private static SLF4JServiceProvider findProvider() {
+        ClassLoader cl = CliLoggerProvider.class.getClassLoader();
+        for (SLF4JServiceProvider provider : 
ServiceLoader.load(SLF4JServiceProvider.class, cl)) {
+            if (!(provider instanceof CliLoggerProvider)) {
+                return provider;
+            }
+        }
+        return new NOP_FallbackServiceProvider();
+    }
+
+    /**
+     * The loggers created before the logging is configured stand in for the 
loggers of the provider on the classpath,
+     * which they log with once it is.
+     */
+    static final class CliLoggerFactory implements ILoggerFactory {
+
+        private final Map<String, SubstituteLogger> loggers = new 
ConcurrentHashMap<>();
+        private volatile ILoggerFactory delegate;
+
+        @Override
+        public Logger getLogger(String name) {
+            ILoggerFactory factory = delegate;
+            if (factory != null) {
+                return factory.getLogger(name);
+            }
+            synchronized (this) {
+                factory = delegate;
+                if (factory != null) {
+                    return factory.getLogger(name);
+                }
+                // a substitute logger without a delegate logs nothing
+                return loggers.computeIfAbsent(name, n -> new 
SubstituteLogger(n, null, true));
+            }
+        }
+
+        synchronized void delegateTo(ILoggerFactory factory) {
+            if (delegate == null) {
+                loggers.forEach((name, logger) -> 
logger.setDelegate(factory.getLogger(name)));
+                delegate = factory;
+            }
+        }
+    }
+
+    /**
+     * The MDC of the provider on the classpath, which its layouts read, 
created when something first uses the MDC.
+     */
+    static final class CliMDCAdapter implements MDCAdapter {
+
+        private final CliLoggerProvider provider;
+
+        CliMDCAdapter(CliLoggerProvider provider) {
+            this.provider = provider;
+        }
+
+        private MDCAdapter adapter() {
+            return provider.delegate().getMDCAdapter();
+        }
+
+        @Override
+        public void put(String key, String val) {
+            adapter().put(key, val);
+        }
+
+        @Override
+        public String get(String key) {
+            return adapter().get(key);
+        }
+
+        @Override
+        public void remove(String key) {
+            adapter().remove(key);
+        }
+
+        @Override
+        public void clear() {
+            adapter().clear();
+        }
+
+        @Override
+        public Map<String, String> getCopyOfContextMap() {
+            return adapter().getCopyOfContextMap();
+        }
+
+        @Override
+        public void setContextMap(Map<String, String> contextMap) {
+            adapter().setContextMap(contextMap);
+        }
+
+        @Override
+        public void pushByKey(String key, String value) {
+            adapter().pushByKey(key, value);
+        }
+
+        @Override
+        public String popByKey(String key) {
+            return adapter().popByKey(key);
+        }
+
+        @Override
+        public Deque<String> getCopyOfDequeByKey(String key) {
+            return adapter().getCopyOfDequeByKey(key);
+        }
+
+        @Override
+        public void clearDequeByKey(String key) {
+            adapter().clearDequeByKey(key);
+        }
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/CliLogging.java
 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/CliLogging.java
new file mode 100644
index 000000000000..4605281da79f
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/CliLogging.java
@@ -0,0 +1,93 @@
+/*
+ * 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.camel.dsl.jbang.run.common;
+
+/**
+ * Installs the SLF4J provider of the CLI ({@link CliLoggerProvider}). A class 
of its own without SLF4J types, so that a
+ * command that never logs, such as camel version, loads no class of SLF4J.
+ */
+public final class CliLogging {
+
+    // the system properties of SLF4J for the provider, and for what it 
reports about itself
+    static final String PROVIDER_PROPERTY = "slf4j.provider";
+    static final String VERBOSITY_PROPERTY = "slf4j.internal.verbosity";
+
+    // the name of CliLoggerProvider, without loading it
+    static final String PROVIDER = 
"org.apache.camel.dsl.jbang.run.common.CliLoggerProvider";
+
+    // whether the CLI configured the logging, and what the provider does then 
once SLF4J chose it
+    private static volatile boolean configured;
+    private static Runnable onConfigured;
+
+    private CliLogging() {
+    }
+
+    /**
+     * Makes SLF4J use the provider of the CLI, unless another one is asked 
for. Call it first thing in the main method
+     * of the CLI, before anything creates a logger.
+     */
+    public static void install() {
+        if (System.getProperty(PROVIDER_PROPERTY) == null) {
+            System.setProperty(PROVIDER_PROPERTY, PROVIDER);
+            if (System.getProperty(VERBOSITY_PROPERTY) == null) {
+                // SLF4J tells on stderr which provider it loads, when it is 
given by the system property
+                System.setProperty(VERBOSITY_PROPERTY, "WARN");
+            }
+        }
+    }
+
+    /**
+     * Whether the loggers of the CLI log nothing yet, as the CLI did not 
configure the logging: then nothing logged to
+     * log4j, and log4j is not started.
+     */
+    static boolean isDeferred() {
+        return !configured && 
PROVIDER.equals(System.getProperty(PROVIDER_PROPERTY));
+    }
+
+    /**
+     * The CLI configured log4j: from now on the loggers of the CLI log with 
it. The CLI calls it when it configures
+     * log4j, see {@link RuntimeUtil#configureLog}.
+     */
+    public static void loggingConfigured() {
+        Runnable task;
+        synchronized (CliLogging.class) {
+            configured = true;
+            task = onConfigured;
+        }
+        if (task != null) {
+            task.run();
+        }
+    }
+
+    // for the tests: as in a new JVM
+    static synchronized void reset() {
+        configured = false;
+        onConfigured = null;
+    }
+
+    // SLF4J chose the provider of the CLI
+    static void bound(Runnable task) {
+        boolean now;
+        synchronized (CliLogging.class) {
+            onConfigured = task;
+            now = configured;
+        }
+        if (now) {
+            task.run();
+        }
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/RuntimeUtil.java
 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/RuntimeUtil.java
index 5c43df8b4742..ee2acf78112e 100644
--- 
a/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/RuntimeUtil.java
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/main/java/org/apache/camel/dsl/jbang/run/common/RuntimeUtil.java
@@ -169,9 +169,11 @@ public final class RuntimeUtil {
                 System.setProperty("pid", Long.toString(pid));
                 // make it possible to manage log4j via JMX and camel-cli
                 System.setProperty("log4j2.disable.jmx", "false");
-                if (isOff(level, location) && !isLog4jConfigured()) {
+                if (isOff(level, location) && (CliLogging.isDeferred() || 
!isLog4jConfigured())) {
                     // most commands log nothing with the logging off, and 
log4j takes about 200 ms to configure: log4j
-                    // configures itself, with the logging off, when something 
first logs
+                    // configures itself, with the logging off, when something 
first logs. With the SLF4J provider of
+                    // the CLI nothing logs to log4j yet, so log4j is not even 
asked whether it is configured, as that
+                    // starts it (CAMEL-26937)
                     System.setProperty(CONFIGURATION_FILE, OFF_CONFIG);
                     deferred = location;
                     configured = location;
@@ -199,6 +201,8 @@ public final class RuntimeUtil {
         }
 
         setRootLoggingLevel(level);
+        // log4j is configured: the loggers of the SLF4J provider of the CLI 
log with it from now on
+        CliLogging.loggingConfigured();
     }
 
     private static boolean isOff(String level, String location) {
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/CliLoggerProviderTest.java
 
b/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/CliLoggerProviderTest.java
new file mode 100644
index 000000000000..af9d8fd6228d
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/CliLoggerProviderTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.camel.dsl.jbang.run.common;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.Test;
+import org.slf4j.ILoggerFactory;
+import org.slf4j.Logger;
+import org.slf4j.spi.MDCAdapter;
+import org.slf4j.spi.SLF4JServiceProvider;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The SLF4J provider of the CLI logs nothing until the CLI configures the 
logging, without starting the provider on the
+ * classpath (log4j), and then logs with it (CAMEL-26937). The provider is not 
installed in this JVM: the tests use an
+ * instance of their own.
+ */
+class CliLoggerProviderTest {
+
+    private final AtomicInteger started = new AtomicInteger();
+    private final SLF4JServiceProvider log4j = 
mock(SLF4JServiceProvider.class);
+    private final ILoggerFactory log4jLoggers = mock(ILoggerFactory.class);
+    private final MDCAdapter log4jMdc = mock(MDCAdapter.class);
+
+    private CliLoggerProvider provider() {
+        when(log4j.getLoggerFactory()).thenReturn(log4jLoggers);
+        when(log4j.getMDCAdapter()).thenReturn(log4jMdc);
+        return new CliLoggerProvider(() -> {
+            started.incrementAndGet();
+            return log4j;
+        });
+    }
+
+    @Test
+    void loggerLogsNothingBeforeTheLoggingIsConfigured() {
+        CliLoggerProvider provider = provider();
+
+        Logger logger = 
provider.getLoggerFactory().getLogger("org.apache.camel.util.FileUtil");
+        logger.error("not logged");
+
+        assertThat(logger.isErrorEnabled()).isFalse();
+        assertThat(started).as("the provider on the classpath is not 
started").hasValue(0);
+    }
+
+    @Test
+    void choosingTheProviderDoesNotStartLog4j() {
+        CliLoggerProvider provider = provider();
+
+        // SLF4J asks for the MDC adapter when it chooses the provider
+        assertThat(provider.getMDCAdapter()).isNotNull();
+
+        assertThat(started).hasValue(0);
+    }
+
+    @Test
+    void loggerCreatedBeforeLogsWithTheProviderOnceConfigured() {
+        CliLoggerProvider provider = provider();
+        Logger early = provider.getLoggerFactory().getLogger("early");
+        Logger log4jLogger = mock(Logger.class);
+        when(log4jLogger.isInfoEnabled()).thenReturn(true);
+        when(log4jLoggers.getLogger("early")).thenReturn(log4jLogger);
+
+        provider.configured();
+        early.info("hello {}", "world");
+
+        assertThat(early.isInfoEnabled()).isTrue();
+        verify(log4jLogger).info("hello {}", "world");
+        assertThat(started).hasValue(1);
+    }
+
+    @Test
+    void loggerCreatedAfterIsTheLoggerOfTheProvider() {
+        CliLoggerProvider provider = provider();
+        Logger log4jLogger = mock(Logger.class);
+        when(log4jLoggers.getLogger("late")).thenReturn(log4jLogger);
+
+        provider.configured();
+
+        
assertThat(provider.getLoggerFactory().getLogger("late")).isSameAs(log4jLogger);
+    }
+
+    @Test
+    void configuredTwiceStartsTheProviderOnce() {
+        CliLoggerProvider provider = provider();
+
+        provider.configured();
+        provider.configured();
+
+        assertThat(started).hasValue(1);
+    }
+
+    @Test
+    void mdcIsTheMdcOfTheProvider() {
+        CliLoggerProvider provider = provider();
+
+        provider.getMDCAdapter().put("camel.exchangeId", "1");
+
+        verify(log4jMdc).put("camel.exchangeId", "1");
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/CliLoggingTest.java
 
b/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/CliLoggingTest.java
new file mode 100644
index 000000000000..acdf54ae9bf4
--- /dev/null
+++ 
b/dsl/camel-jbang/camel-jbang-run/src/test/java/org/apache/camel/dsl/jbang/run/common/CliLoggingTest.java
@@ -0,0 +1,83 @@
+/*
+ * 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.camel.dsl.jbang.run.common;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junitpioneer.jupiter.ClearSystemProperty;
+import org.junitpioneer.jupiter.SetSystemProperty;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The CLI tells its SLF4J provider when it configured the logging, also when 
SLF4J chooses the provider only after that
+ * (CAMEL-26937).
+ */
+class CliLoggingTest {
+
+    private final AtomicInteger configured = new AtomicInteger();
+
+    @BeforeEach
+    @AfterEach
+    void newJvm() {
+        CliLogging.reset();
+    }
+
+    @Test
+    void providerChosenBeforeTheLoggingIsConfigured() {
+        CliLogging.bound(configured::incrementAndGet);
+        assertThat(configured).hasValue(0);
+
+        CliLogging.loggingConfigured();
+
+        assertThat(configured).hasValue(1);
+    }
+
+    @Test
+    void providerChosenAfterTheLoggingIsConfigured() {
+        CliLogging.loggingConfigured();
+
+        CliLogging.bound(configured::incrementAndGet);
+
+        assertThat(configured).hasValue(1);
+    }
+
+    @Test
+    @SetSystemProperty(key = CliLogging.PROVIDER_PROPERTY, value = 
CliLogging.PROVIDER)
+    void deferredUntilTheLoggingIsConfigured() {
+        assertThat(CliLogging.isDeferred()).isTrue();
+
+        CliLogging.loggingConfigured();
+
+        assertThat(CliLogging.isDeferred()).isFalse();
+    }
+
+    @Test
+    @ClearSystemProperty(key = CliLogging.PROVIDER_PROPERTY)
+    void notDeferredWithAnotherProvider() {
+        // a JVM that did not start from the main method of the CLI, such as 
the tests of the commands
+        assertThat(CliLogging.isDeferred()).isFalse();
+    }
+
+    @Test
+    void providerName() {
+        
assertThat(CliLogging.PROVIDER).isEqualTo(CliLoggerProvider.class.getName());
+    }
+}
diff --git 
a/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/CamelLauncher.java
 
b/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/CamelLauncher.java
index af7fef3a6611..1909903d9697 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/CamelLauncher.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/main/java/org/apache/camel/dsl/jbang/launcher/CamelLauncher.java
@@ -17,6 +17,7 @@
 package org.apache.camel.dsl.jbang.launcher;
 
 import org.apache.camel.dsl.jbang.core.common.LauncherHelper;
+import org.apache.camel.dsl.jbang.run.common.CliLogging;
 
 /**
  * Main class for the Camel CLI Fat-Jar Launcher.
@@ -32,6 +33,9 @@ public class CamelLauncher {
      * @param args command line arguments to pass to Camel CLI
      */
     public static void main(String... args) {
+        // before anything creates a logger: the loggers log nothing until the 
CLI configures the logging, so a command
+        // that turns the logging off does not start log4j
+        CliLogging.install();
         System.setProperty(LauncherHelper.CAMEL_LAUNCHER_PROPERTY, "true");
 
         // The JAR of this class, which the CLI runs again in another process: 
the fat JAR, or the launcher JAR in lib/
diff --git 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/LauncherStartupLoggingTest.java
 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/LauncherStartupLoggingTest.java
index c4d837270610..f9355f035415 100644
--- 
a/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/LauncherStartupLoggingTest.java
+++ 
b/dsl/camel-jbang/camel-launcher/src/test/java/org/apache/camel/dsl/jbang/launcher/LauncherStartupLoggingTest.java
@@ -60,6 +60,17 @@ class LauncherStartupLoggingTest {
         assertNoLogging(classes);
     }
 
+    @Test
+    void aCommandWithTheLoggingOffDoesNotStartLog4j() throws Exception {
+        // camel doc creates loggers (of the catalog), which made log4j start, 
only to log nothing (CAMEL-26937)
+        List<String> classes = run(CamelLauncher.class.getName(), "doc", 
"timer");
+
+        assertThat(classes).as("the SLF4J provider of the CLI")
+                
.contains("org.apache.camel.dsl.jbang.run.common.CliLoggerProvider");
+        assertThat(classes.stream().filter(c -> 
c.startsWith("org.apache.logging.log4j."))).as("log4j is not started")
+                .isEmpty();
+    }
+
     private static void assertNoLogging(List<String> classes) {
         assertThat(classes.stream().filter(c -> 
c.startsWith("org.slf4j."))).as("no logger").isEmpty();
         assertThat(classes.stream().filter(c -> 
c.startsWith("org.apache.logging.log4j.core.appender.")))

Reply via email to