You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by pc...@apache.org on 2025/09/30 12:08:39 UTC
(camel) branch main updated (25fb7376eed -> b5f0dda1455)
This is an automated email from the ASF dual-hosted git repository.
pcongiusti pushed a change to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
from 25fb7376eed CAMEL-22471: camel-jbang - Send command with file location should use absolute path
new 04fece586e1 feat(components): Camel MDC
new cc3bb758a63 feat(components): MDC custom headers and properties
new 9cbf5752445 feat(components): mdc all headers/properties
new e3715c94db4 feat(components): MDC Intercept strategy and UT
new b5f0dda1455 feat(component): MDC docs
The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
bom/camel-bom/pom.xml | 5 +
catalog/camel-allcomponents/pom.xml | 5 +
.../main/camel-main-configuration-metadata.json | 4 +
.../org/apache/camel/catalog/others.properties | 1 +
.../org/apache/camel/catalog/others/mdc.json | 15 ++
components/{camel-tracing => camel-mdc}/pom.xml | 17 +-
.../services/org/apache/camel/mdc-service} | 6 +-
.../services/org/apache/camel/other.properties | 7 +
.../camel-mdc/src/generated/resources/mdc.json | 15 ++
components/camel-mdc/src/main/docs/mdc.adoc | 67 +++++++
.../camel/mdc/MDCProcessorsInterceptStrategy.java | 91 +++++++++
.../main/java/org/apache/camel/mdc/MDCService.java | 207 +++++++++++++++++++++
.../org/apache/camel/mdc/MDCAllHeadersTest.java} | 62 +++---
.../apache/camel/mdc/MDCAllPropertiesTest.java} | 62 +++---
.../java/org/apache/camel/mdc/MDCAsyncTest.java | 93 +++++++++
.../org/apache/camel/mdc/MDCAsyncWiretapTest.java | 118 ++++++++++++
.../java/org/apache/camel/mdc/MDCDefaultTest.java} | 57 +++---
.../apache/camel/mdc/MDCSelectedHeadersTest.java} | 69 +++----
.../camel/mdc/MDCSelectedPropertiesTest.java | 84 +++++++++
.../org/apache/camel/mdc}/MyAsyncComponent.java | 2 +-
.../org/apache/camel/mdc}/MyAsyncEndpoint.java | 2 +-
.../org/apache/camel/mdc}/MyAsyncProducer.java | 3 +-
.../src/test/resources/log4j2.properties | 9 +-
components/pom.xml | 1 +
...melMetricsService.java => CamelMDCService.java} | 4 +-
.../java/org/apache/camel/spi/LogListener.java | 12 ++
.../org/apache/camel/processor/LogProcessor.java | 20 ++
...a => MdcConfigurationPropertiesConfigurer.java} | 43 ++---
.../camel-main-configuration-metadata.json | 4 +
...rg.apache.camel.main.MdcConfigurationProperties | 2 +
core/camel-main/src/main/docs/main.adoc | 12 ++
.../org/apache/camel/main/BaseMainSupport.java | 56 +++++-
.../camel/main/MainConfigurationProperties.java | 12 ++
.../camel/main/MdcConfigurationProperties.java | 106 +++++++++++
.../camel/support/processor/CamelLogProcessor.java | 22 +++
.../modules/others/examples/json/mdc.json | 1 +
docs/components/modules/others/nav.adoc | 1 +
docs/components/modules/others/pages/mdc.adoc | 1 +
parent/pom.xml | 5 +
proposals/mdc.adoc | 8 +-
.../maven/packaging/PrepareCamelMainMojo.java | 5 +
41 files changed, 1125 insertions(+), 191 deletions(-)
create mode 100644 catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json
copy components/{camel-tracing => camel-mdc}/pom.xml (83%)
copy components/{camel-soap/src/generated/resources/org/xmlsoap/schemas/soap/envelope/jaxb.index => camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/mdc-service} (60%)
create mode 100644 components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties
create mode 100644 components/camel-mdc/src/generated/resources/mdc.json
create mode 100644 components/camel-mdc/src/main/docs/mdc.adoc
create mode 100644 components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java
create mode 100644 components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
copy components/{camel-telemetry-dev/src/test/java/org/apache/camel/telemetrydev/DisableEndpointTest.java => camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllHeadersTest.java} (52%)
copy components/{camel-telemetry-dev/src/test/java/org/apache/camel/telemetrydev/DisableEndpointTest.java => camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllPropertiesTest.java} (51%)
create mode 100644 components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
create mode 100644 components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncWiretapTest.java
copy components/{camel-telemetry-dev/src/test/java/org/apache/camel/telemetrydev/DisableEndpointTest.java => camel-mdc/src/test/java/org/apache/camel/mdc/MDCDefaultTest.java} (53%)
copy components/{camel-telemetry/src/test/java/org/apache/camel/telemetry/DisableEndpointTest.java => camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedHeadersTest.java} (50%)
create mode 100644 components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedPropertiesTest.java
copy {core/camel-core/src/test/java/org/apache/camel/processor/async => components/camel-mdc/src/test/java/org/apache/camel/mdc}/MyAsyncComponent.java (97%)
copy {core/camel-core/src/test/java/org/apache/camel/processor/async => components/camel-mdc/src/test/java/org/apache/camel/mdc}/MyAsyncEndpoint.java (98%)
copy {core/camel-core/src/test/java/org/apache/camel/processor/async => components/camel-mdc/src/test/java/org/apache/camel/mdc}/MyAsyncProducer.java (98%)
copy {core/camel-cloud => components/camel-mdc}/src/test/resources/log4j2.properties (79%)
copy core/camel-api/src/main/java/org/apache/camel/spi/{CamelMetricsService.java => CamelMDCService.java} (86%)
copy core/camel-main/src/generated/java/org/apache/camel/main/{TelemetryDevConfigurationPropertiesConfigurer.java => MdcConfigurationPropertiesConfigurer.java} (50%)
create mode 100644 core/camel-main/src/generated/resources/META-INF/services/org/apache/camel/configurer/org.apache.camel.main.MdcConfigurationProperties
create mode 100644 core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java
create mode 120000 docs/components/modules/others/examples/json/mdc.json
create mode 120000 docs/components/modules/others/pages/mdc.adoc
(camel) 03/05: feat(components): mdc all headers/properties
Posted by pc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
pcongiusti pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
commit 9cbf57524457df8f558f68280dd5df93a1f941b9
Author: Pasquale Congiusti <pa...@gmail.com>
AuthorDate: Thu Sep 25 09:10:56 2025 +0200
feat(components): mdc all headers/properties
---
.../main/java/org/apache/camel/mdc/MDCService.java | 37 +++++++++++++++++++---
1 file changed, 33 insertions(+), 4 deletions(-)
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
index eaf890f93cf..bd38d6a9a16 100644
--- a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
@@ -93,6 +93,12 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
camelContext.getCamelContextExtension().addLogListener(new TracingLogListener());
}
+ @Override
+ protected void doStart() throws Exception {
+ super.doStart();
+ LOG.info("Mapped Diagnostic Context (MDC) enabled");
+ }
+
private final class TracingLogListener implements LogListener {
@Override
@@ -101,12 +107,18 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
// Default values
prepareMDC(exchange);
if (getCustomHeaders() != null) {
- // User headers values
- userSelectedHeadersMDC(exchange);
+ if (getCustomHeaders().equals("*")){
+ allHeadersMDC(exchange);
+ } else {
+ userSelectedHeadersMDC(exchange);
+ }
}
if (getCustomProperties() != null) {
- // User headers values
- userSelectedPropertiesMDC(exchange);
+ if (getCustomProperties().equals("*")){
+ allPropertiesMDC(exchange);
+ } else {
+ userSelectedPropertiesMDC(exchange);
+ }
}
} catch (Exception t) {
// This exception is ignored
@@ -149,6 +161,14 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
}
}
}
+ // Include all available headers
+ private void allHeadersMDC(Exchange exchange) {
+ for (String header : exchange.getIn().getHeaders().keySet()) {
+ if (exchange.getIn().getHeader(header) != null) {
+ MDC.put(header, exchange.getIn().getHeader(header, String.class));
+ }
+ }
+ }
// Include those properties selected by the user
private void userSelectedPropertiesMDC(Exchange exchange) {
@@ -158,6 +178,15 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
}
}
}
+
+ // Include all available properties
+ private void allPropertiesMDC(Exchange exchange) {
+ for (String property : exchange.getAllProperties().keySet()) {
+ if (exchange.getProperty(property) != null) {
+ MDC.put(property, exchange.getProperty(property, String.class));
+ }
+ }
+ }
}
}
(camel) 04/05: feat(components): MDC Intercept strategy and UT
Posted by pc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
pcongiusti pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
commit e3715c94db48bd21fae6d9bb44c9cb9494c595bf
Author: Pasquale Congiusti <pa...@gmail.com>
AuthorDate: Thu Sep 25 12:00:23 2025 +0200
feat(components): MDC Intercept strategy and UT
* Required to wrap any Camel processor
* Unit test to cover main use cases
---
.../camel/mdc/MDCProcessorsInterceptStrategy.java | 64 +++++++++
.../main/java/org/apache/camel/mdc/MDCService.java | 158 +++++++++++----------
.../org/apache/camel/mdc/MDCAllHeadersTest.java | 79 +++++++++++
.../org/apache/camel/mdc/MDCAllPropertiesTest.java | 79 +++++++++++
.../java/org/apache/camel/mdc/MDCAsyncTest.java | 120 ++++++++++++++++
.../java/org/apache/camel/mdc/MDCDefaultTest.java | 74 ++++++++++
.../apache/camel/mdc/MDCSelectedHeadersTest.java | 84 +++++++++++
.../camel/mdc/MDCSelectedPropertiesTest.java | 84 +++++++++++
.../camel-mdc/src/test/resources/log4j2.properties | 6 +-
9 files changed, 672 insertions(+), 76 deletions(-)
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java
new file mode 100644
index 00000000000..3306a40e90d
--- /dev/null
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java
@@ -0,0 +1,64 @@
+/*
+ * 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.mdc;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.NamedNode;
+import org.apache.camel.Processor;
+import org.apache.camel.spi.InterceptStrategy;
+import org.apache.camel.support.processor.DelegateAsyncProcessor;
+
+/**
+ * MDCProcessorsInterceptStrategy is used to wrap each processor calls and generate the MDC context for each process
+ * execution.
+ */
+public class MDCProcessorsInterceptStrategy implements InterceptStrategy {
+
+ private MDCService mdcService;
+
+ public MDCProcessorsInterceptStrategy(MDCService mdcService) {
+ this.mdcService = mdcService;
+ }
+
+ @Override
+ public Processor wrapProcessorInInterceptors(
+ CamelContext camelContext,
+ NamedNode processorDefinition, Processor target, Processor nextTarget)
+ throws Exception {
+ return new DelegateAsyncProcessor(new TraceProcessor(target));
+ }
+
+ private class TraceProcessor implements Processor {
+ private final Processor target;
+
+ public TraceProcessor(Processor target) {
+ this.target = target;
+ }
+
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ mdcService.setMDC(exchange);
+ try {
+ target.process(exchange);
+ } finally {
+ mdcService.unsetMDC();
+ }
+ }
+ }
+
+}
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
index bd38d6a9a16..5ac3a429881 100644
--- a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
@@ -22,6 +22,7 @@ import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.spi.CamelLogger;
import org.apache.camel.spi.CamelMDCService;
+import org.apache.camel.spi.InterceptStrategy;
import org.apache.camel.spi.LogListener;
import org.apache.camel.spi.annotations.JdkService;
import org.apache.camel.support.service.ServiceSupport;
@@ -33,12 +34,12 @@ import org.slf4j.MDC;
@JdkService("mdc-service")
public class MDCService extends ServiceSupport implements CamelMDCService {
- private String MDC_BREADCRUMB_ID = "camel.breadcrumbId";
- private String MDC_EXCHANGE_ID = "camel.exchangeId";
- private String MDC_MESSAGE_ID = "camel.messageId";
- private String MDC_CORRELATION_ID = "camel.correlationId";
- private String MDC_ROUTE_ID = "camel.routeId";
- private String MDC_CAMEL_CONTEXT_ID = "camel.contextId";
+ static String MDC_BREADCRUMB_ID = "camel.breadcrumbId";
+ static String MDC_EXCHANGE_ID = "camel.exchangeId";
+ static String MDC_MESSAGE_ID = "camel.messageId";
+ static String MDC_CORRELATION_ID = "camel.correlationId";
+ static String MDC_ROUTE_ID = "camel.routeId";
+ static String MDC_CAMEL_CONTEXT_ID = "camel.contextId";
private static final Logger LOG = LoggerFactory.getLogger(MDCService.class);
@@ -90,7 +91,9 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
@Override
public void doInit() {
ObjectHelper.notNull(camelContext, "CamelContext", this);
- camelContext.getCamelContextExtension().addLogListener(new TracingLogListener());
+ camelContext.getCamelContextExtension().addLogListener(new MDCLogListener());
+ InterceptStrategy interceptStrategy = new MDCProcessorsInterceptStrategy(this);
+ camelContext.getCamelContextExtension().addInterceptStrategy(interceptStrategy);
}
@Override
@@ -99,92 +102,101 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
LOG.info("Mapped Diagnostic Context (MDC) enabled");
}
- private final class TracingLogListener implements LogListener {
-
- @Override
- public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
- try {
- // Default values
- prepareMDC(exchange);
- if (getCustomHeaders() != null) {
- if (getCustomHeaders().equals("*")){
- allHeadersMDC(exchange);
- } else {
- userSelectedHeadersMDC(exchange);
- }
+ protected void setMDC(Exchange exchange) {
+ try {
+ // Default values
+ prepareMDC(exchange);
+ if (getCustomHeaders() != null) {
+ if (getCustomHeaders().equals("*")) {
+ allHeadersMDC(exchange);
+ } else {
+ userSelectedHeadersMDC(exchange);
}
- if (getCustomProperties() != null) {
- if (getCustomProperties().equals("*")){
- allPropertiesMDC(exchange);
- } else {
- userSelectedPropertiesMDC(exchange);
- }
+ }
+ if (getCustomProperties() != null) {
+ if (getCustomProperties().equals("*")) {
+ allPropertiesMDC(exchange);
+ } else {
+ userSelectedPropertiesMDC(exchange);
}
- } catch (Exception t) {
- // This exception is ignored
- LOG.warn("MDC: failed to store MDC data. This exception is ignored.", t);
}
+ } catch (Exception t) {
+ // This exception is ignored
+ LOG.warn("MDC: failed to store MDC data. This exception is ignored.", t);
+ }
+ }
+
+ public void unsetMDC() {
+ MDC.clear();
+ }
+
+ private final class MDCLogListener implements LogListener {
+
+ @Override
+ public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
+ setMDC(exchange);
return message;
}
@Override
public void afterLog(Exchange exchange, CamelLogger camelLogger, String message) {
- MDC.clear();
+ unsetMDC();
}
+ }
- // Default basic MDC properties to set
- private void prepareMDC(Exchange exchange) {
- MDC.put(MDC_EXCHANGE_ID, exchange.getExchangeId());
- MDC.put(MDC_MESSAGE_ID, exchange.getMessage().getMessageId());
- MDC.put(MDC_CAMEL_CONTEXT_ID, exchange.getContext().getName());
- // Backward compatibility: this info may not be longer widely used
- String corrId = exchange.getProperty(ExchangePropertyKey.CORRELATION_ID, String.class);
- if (corrId != null) {
- MDC.put(MDC_CORRELATION_ID, corrId);
- }
- // Backward compatibility: this info may not be longer widely used
- String breadcrumbId = exchange.getIn().getHeader(Exchange.BREADCRUMB_ID, String.class);
- if (breadcrumbId != null) {
- MDC.put(MDC_BREADCRUMB_ID, breadcrumbId);
- }
- String routeId = exchange.getFromRouteId();
- if (routeId != null) {
- MDC.put(MDC_ROUTE_ID, routeId);
- }
+ // Default basic MDC properties to set
+ private void prepareMDC(Exchange exchange) {
+ MDC.put(MDC_EXCHANGE_ID, exchange.getExchangeId());
+ MDC.put(MDC_MESSAGE_ID, exchange.getMessage().getMessageId());
+ MDC.put(MDC_CAMEL_CONTEXT_ID, exchange.getContext().getName());
+ // Backward compatibility: this info may not be longer widely used
+ String corrId = exchange.getProperty(ExchangePropertyKey.CORRELATION_ID, String.class);
+ if (corrId != null) {
+ MDC.put(MDC_CORRELATION_ID, corrId);
+ }
+ // Backward compatibility: this info may not be longer widely used
+ String breadcrumbId = exchange.getIn().getHeader(Exchange.BREADCRUMB_ID, String.class);
+ if (breadcrumbId != null) {
+ MDC.put(MDC_BREADCRUMB_ID, breadcrumbId);
}
+ String routeId = exchange.getFromRouteId();
+ if (routeId != null) {
+ MDC.put(MDC_ROUTE_ID, routeId);
+ }
+ }
- // Include those headers selected by the user
- private void userSelectedHeadersMDC(Exchange exchange) {
- for (String customHeader : getCustomHeaders().split(",")) {
- if (exchange.getIn().getHeader(customHeader) != null) {
- MDC.put(customHeader, exchange.getIn().getHeader(customHeader, String.class));
- }
+ // Include those headers selected by the user
+ private void userSelectedHeadersMDC(Exchange exchange) {
+ for (String customHeader : getCustomHeaders().split(",")) {
+ if (exchange.getIn().getHeader(customHeader) != null) {
+ MDC.put(customHeader, exchange.getIn().getHeader(customHeader, String.class));
}
}
- // Include all available headers
- private void allHeadersMDC(Exchange exchange) {
- for (String header : exchange.getIn().getHeaders().keySet()) {
- if (exchange.getIn().getHeader(header) != null) {
- MDC.put(header, exchange.getIn().getHeader(header, String.class));
- }
+ }
+
+ // Include all available headers
+ private void allHeadersMDC(Exchange exchange) {
+ for (String header : exchange.getIn().getHeaders().keySet()) {
+ if (exchange.getIn().getHeader(header) != null) {
+ MDC.put(header, exchange.getIn().getHeader(header, String.class));
}
}
+ }
- // Include those properties selected by the user
- private void userSelectedPropertiesMDC(Exchange exchange) {
- for (String customProperty : getCustomProperties().split(",")) {
- if (exchange.getProperty(customProperty) != null) {
- MDC.put(customProperty, exchange.getProperty(customProperty, String.class));
- }
+ // Include those properties selected by the user
+ private void userSelectedPropertiesMDC(Exchange exchange) {
+ for (String customProperty : getCustomProperties().split(",")) {
+ if (exchange.getProperty(customProperty) != null) {
+ MDC.put(customProperty, exchange.getProperty(customProperty, String.class));
}
}
+ }
- // Include all available properties
- private void allPropertiesMDC(Exchange exchange) {
- for (String property : exchange.getAllProperties().keySet()) {
- if (exchange.getProperty(property) != null) {
- MDC.put(property, exchange.getProperty(property, String.class));
- }
+ // Include all available properties
+ private void allPropertiesMDC(Exchange exchange) {
+ for (String property : exchange.getAllProperties().keySet()) {
+ if (exchange.getProperty(property) != null) {
+ MDC.put(property, exchange.getProperty(property, String.class));
}
}
}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllHeadersTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllHeadersTest.java
new file mode 100644
index 00000000000..14ab6a56c3e
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllHeadersTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.mdc;
+
+import java.io.IOException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+public class MDCAllHeadersTest extends ExchangeTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCSelectedPropertiesTest.class);
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ MDCService mdcSvc = new MDCService();
+ mdcSvc.setCustomHeaders("*");
+ CamelContext context = super.createCamelContext();
+ CamelContextAware.trySetCamelContext(mdcSvc, context);
+ mdcSvc.init(context);
+ return context;
+ }
+
+ @Test
+ void testRouteSingleRequest() throws IOException {
+ template.request("direct:start", null);
+ // We should get no MDC after the route has been executed
+ assertEquals(0, MDC.getCopyOfContextMap().size());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .routeId("start")
+ .log("A message")
+ .setHeader("head1", simple("Header1"))
+ .setHeader("head2", simple("Header2"))
+ .process(exchange -> {
+ LOG.info("A process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertEquals("Header1", MDC.get("head1"));
+ assertEquals("Header2", MDC.get("head2"));
+ })
+ .to("log:info");
+ }
+ };
+ }
+
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllPropertiesTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllPropertiesTest.java
new file mode 100644
index 00000000000..57562b61728
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAllPropertiesTest.java
@@ -0,0 +1,79 @@
+/*
+ * 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.mdc;
+
+import java.io.IOException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+public class MDCAllPropertiesTest extends ExchangeTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCSelectedPropertiesTest.class);
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ MDCService mdcSvc = new MDCService();
+ mdcSvc.setCustomProperties("*");
+ CamelContext context = super.createCamelContext();
+ CamelContextAware.trySetCamelContext(mdcSvc, context);
+ mdcSvc.init(context);
+ return context;
+ }
+
+ @Test
+ void testRouteSingleRequest() throws IOException {
+ template.request("direct:start", null);
+ // We should get no MDC after the route has been executed
+ assertEquals(0, MDC.getCopyOfContextMap().size());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .routeId("start")
+ .log("A message")
+ .setProperty("prop1", simple("Property1"))
+ .setProperty("prop2", simple("Property2"))
+ .process(exchange -> {
+ LOG.info("A process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertEquals("Property1", MDC.get("prop1"));
+ assertEquals("Property2", MDC.get("prop2"));
+ })
+ .to("log:info");
+ }
+ };
+ }
+
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
new file mode 100644
index 00000000000..7a5c2284a1d
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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.mdc;
+
+import java.io.IOException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit5.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+public class MDCAsyncTest extends ExchangeTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCAsyncTest.class);
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ MDCService mdcSvc = new MDCService();
+ mdcSvc.setCustomHeaders("*");
+ mdcSvc.setCustomProperties("*");
+ CamelContext context = super.createCamelContext();
+ CamelContextAware.trySetCamelContext(mdcSvc, context);
+ mdcSvc.init(context);
+ return context;
+ }
+
+ @Test
+ void testRouteSingleRequest() throws IOException, InterruptedException {
+ MockEndpoint mock = getMockEndpoint("mock:end");
+ mock.expectedMessageCount(1);
+ mock.setAssertPeriod(5000);
+ context.createProducerTemplate().sendBody("direct:start", null);
+ mock.assertIsSatisfied(1000);
+ // We should get no MDC after the route has been executed
+ assertEquals(0, MDC.getCopyOfContextMap().size());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .setBody()
+ .simple("start")
+ .log("start: ${exchangeId}")
+ .to("direct:a")
+ .wireTap("direct:b");
+
+ from("direct:a")
+ .setProperty("prop1", simple("Property1"))
+ .setHeader("head", simple("Header1"))
+ .process(exchange -> {
+ LOG.info("Direct:a process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertEquals("Header1", MDC.get("head"));
+ assertEquals("Property1", MDC.get("prop1"));
+ assertNull(MDC.get("prop2"));
+ // We store the exchange of this execution in a property
+ // as we will use this property to evaluate the exchange in the direct:b execution
+ exchange.setProperty("directa-exchange", exchange.getExchangeId());
+ })
+ .setBody()
+ .simple("Direct a")
+ .log("directa: ${exchangeId}");
+
+ from("direct:b")
+ .setProperty("prop2", simple("Property2"))
+ .setHeader("head", simple("Header2"))
+ .process(exchange -> {
+ LOG.info("Direct:b process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertEquals("Header2", MDC.get("head"));
+ // NOTE: properties are shared
+ assertEquals("Property1", MDC.get("prop1"));
+ assertEquals("Property2", MDC.get("prop2"));
+ // We use as support storage the same properties
+ assertNotEquals(exchange.getProperty("directa-exchange"), MDC.get(MDCService.MDC_EXCHANGE_ID));
+ })
+ .delay(2000)
+ .setBody()
+ .simple("Direct b")
+ .log("directb: ${exchangeId}")
+ .to("mock:end");
+ }
+ };
+ }
+
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCDefaultTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCDefaultTest.java
new file mode 100644
index 00000000000..162d5ae5cb7
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCDefaultTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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.mdc;
+
+import java.io.IOException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+public class MDCDefaultTest extends ExchangeTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCDefaultTest.class);
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ MDCService mdcSvc = new MDCService();
+ CamelContext context = super.createCamelContext();
+ CamelContextAware.trySetCamelContext(mdcSvc, context);
+ mdcSvc.init(context);
+ return context;
+ }
+
+ @Test
+ void testRouteSingleRequest() throws IOException {
+ template.request("direct:start", null);
+ // We should get no MDC after the route has been executed
+ assertEquals(0, MDC.getCopyOfContextMap().size());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .routeId("start")
+ .log("A message")
+ .process(exchange -> {
+ LOG.info("A process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ })
+ .to("log:info");
+ }
+ };
+ }
+
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedHeadersTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedHeadersTest.java
new file mode 100644
index 00000000000..3ff151b206c
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedHeadersTest.java
@@ -0,0 +1,84 @@
+/*
+ * 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.mdc;
+
+import java.io.IOException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+public class MDCSelectedHeadersTest extends ExchangeTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCAllPropertiesTest.class);
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ MDCService mdcSvc = new MDCService();
+ mdcSvc.setCustomHeaders("head1,head2,head3");
+ CamelContext context = super.createCamelContext();
+ CamelContextAware.trySetCamelContext(mdcSvc, context);
+ mdcSvc.init(context);
+ return context;
+ }
+
+ @Test
+ void testRouteSingleRequest() throws IOException {
+ template.request("direct:start", null);
+ // We should get no MDC after the route has been executed
+ assertEquals(0, MDC.getCopyOfContextMap().size());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .routeId("start")
+ .log("A message")
+ .setHeader("head1", simple("Header1"))
+ .setHeader("head2", simple("Header2"))
+ // head3 is missing on purpose!
+ .setHeader("head4", simple("Header4"))
+ .process(exchange -> {
+ LOG.info("A process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertEquals("Header1", MDC.get("head1"));
+ assertEquals("Header2", MDC.get("head2"));
+ assertNull(MDC.get("head3"));
+ assertNull(MDC.get("head4"));
+ })
+ .to("log:info");
+ }
+ };
+ }
+
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedPropertiesTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedPropertiesTest.java
new file mode 100644
index 00000000000..e3fa275a737
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCSelectedPropertiesTest.java
@@ -0,0 +1,84 @@
+/*
+ * 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.mdc;
+
+import java.io.IOException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit5.ExchangeTestSupport;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+public class MDCSelectedPropertiesTest extends ExchangeTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCAllPropertiesTest.class);
+
+ @Override
+ protected CamelContext createCamelContext() throws Exception {
+ MDCService mdcSvc = new MDCService();
+ mdcSvc.setCustomProperties("prop1,prop2,prop3");
+ CamelContext context = super.createCamelContext();
+ CamelContextAware.trySetCamelContext(mdcSvc, context);
+ mdcSvc.init(context);
+ return context;
+ }
+
+ @Test
+ void testRouteSingleRequest() throws IOException {
+ template.request("direct:start", null);
+ // We should get no MDC after the route has been executed
+ assertEquals(0, MDC.getCopyOfContextMap().size());
+ }
+
+ @Override
+ protected RoutesBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start")
+ .routeId("start")
+ .log("A message")
+ .setProperty("prop1", simple("Property1"))
+ .setProperty("prop2", simple("Property2"))
+ // prop3 is missing on purpose!
+ .setProperty("prop4", simple("Property4"))
+ .process(exchange -> {
+ LOG.info("A process");
+ assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertEquals("Property1", MDC.get("prop1"));
+ assertEquals("Property2", MDC.get("prop2"));
+ assertNull(MDC.get("prop3"));
+ assertNull(MDC.get("prop4"));
+ })
+ .to("log:info");
+ }
+ };
+ }
+
+}
diff --git a/components/camel-mdc/src/test/resources/log4j2.properties b/components/camel-mdc/src/test/resources/log4j2.properties
index c9d7df800c7..590933e3e26 100644
--- a/components/camel-mdc/src/test/resources/log4j2.properties
+++ b/components/camel-mdc/src/test/resources/log4j2.properties
@@ -17,14 +17,14 @@
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
-appender.console.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
+appender.console.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m [%X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{head1}, %X{prop1}, %X{head2}, %X{prop2}]%n
appender.file.type = File
appender.file.name = file
-appender.file.fileName = target/camel-telemetry-test.log
+appender.file.fileName = target/camel-mdc-test.log
appender.file.append = true
appender.file.layout.type = PatternLayout
-appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
+appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m [%X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{head1}, %X{prop1}, %X{head2}, %X{prop2}]%n
rootLogger.level = INFO
rootLogger.appenderRef.file.ref = file
(camel) 02/05: feat(components): MDC custom headers and properties
Posted by pc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
pcongiusti pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
commit cc3bb758a6348ca3b1e94d07acfc4fbc52d5b8ed
Author: Pasquale Congiusti <pa...@gmail.com>
AuthorDate: Wed Sep 24 11:25:19 2025 +0200
feat(components): MDC custom headers and properties
---
.../main/java/org/apache/camel/mdc/MDCService.java | 78 +++++++++++++++++++++-
1 file changed, 76 insertions(+), 2 deletions(-)
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
index 098230b11a0..eaf890f93cf 100644
--- a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
@@ -18,6 +18,7 @@ package org.apache.camel.mdc;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.spi.CamelLogger;
import org.apache.camel.spi.CamelMDCService;
@@ -32,10 +33,20 @@ import org.slf4j.MDC;
@JdkService("mdc-service")
public class MDCService extends ServiceSupport implements CamelMDCService {
+ private String MDC_BREADCRUMB_ID = "camel.breadcrumbId";
+ private String MDC_EXCHANGE_ID = "camel.exchangeId";
+ private String MDC_MESSAGE_ID = "camel.messageId";
+ private String MDC_CORRELATION_ID = "camel.correlationId";
+ private String MDC_ROUTE_ID = "camel.routeId";
+ private String MDC_CAMEL_CONTEXT_ID = "camel.contextId";
+
private static final Logger LOG = LoggerFactory.getLogger(MDCService.class);
private CamelContext camelContext;
+ private String customHeaders;
+ private String customProperties;
+
@Override
public CamelContext getCamelContext() {
return camelContext;
@@ -46,6 +57,22 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
this.camelContext = camelContext;
}
+ public String getCustomHeaders() {
+ return customHeaders;
+ }
+
+ public void setCustomHeaders(String customHeaders) {
+ this.customHeaders = customHeaders;
+ }
+
+ public String getCustomProperties() {
+ return customProperties;
+ }
+
+ public void setCustomProperties(String customProperties) {
+ this.customProperties = customProperties;
+ }
+
/**
* Registers this {@link MDCService} on the {@link CamelContext} if not already registered.
*/
@@ -71,8 +98,16 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
@Override
public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
try {
- // MDC setting here
- MDC.put("exchangeID", exchange.getExchangeId());
+ // Default values
+ prepareMDC(exchange);
+ if (getCustomHeaders() != null) {
+ // User headers values
+ userSelectedHeadersMDC(exchange);
+ }
+ if (getCustomProperties() != null) {
+ // User headers values
+ userSelectedPropertiesMDC(exchange);
+ }
} catch (Exception t) {
// This exception is ignored
LOG.warn("MDC: failed to store MDC data. This exception is ignored.", t);
@@ -84,6 +119,45 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
public void afterLog(Exchange exchange, CamelLogger camelLogger, String message) {
MDC.clear();
}
+
+ // Default basic MDC properties to set
+ private void prepareMDC(Exchange exchange) {
+ MDC.put(MDC_EXCHANGE_ID, exchange.getExchangeId());
+ MDC.put(MDC_MESSAGE_ID, exchange.getMessage().getMessageId());
+ MDC.put(MDC_CAMEL_CONTEXT_ID, exchange.getContext().getName());
+ // Backward compatibility: this info may not be longer widely used
+ String corrId = exchange.getProperty(ExchangePropertyKey.CORRELATION_ID, String.class);
+ if (corrId != null) {
+ MDC.put(MDC_CORRELATION_ID, corrId);
+ }
+ // Backward compatibility: this info may not be longer widely used
+ String breadcrumbId = exchange.getIn().getHeader(Exchange.BREADCRUMB_ID, String.class);
+ if (breadcrumbId != null) {
+ MDC.put(MDC_BREADCRUMB_ID, breadcrumbId);
+ }
+ String routeId = exchange.getFromRouteId();
+ if (routeId != null) {
+ MDC.put(MDC_ROUTE_ID, routeId);
+ }
+ }
+
+ // Include those headers selected by the user
+ private void userSelectedHeadersMDC(Exchange exchange) {
+ for (String customHeader : getCustomHeaders().split(",")) {
+ if (exchange.getIn().getHeader(customHeader) != null) {
+ MDC.put(customHeader, exchange.getIn().getHeader(customHeader, String.class));
+ }
+ }
+ }
+
+ // Include those properties selected by the user
+ private void userSelectedPropertiesMDC(Exchange exchange) {
+ for (String customProperty : getCustomProperties().split(",")) {
+ if (exchange.getProperty(customProperty) != null) {
+ MDC.put(customProperty, exchange.getProperty(customProperty, String.class));
+ }
+ }
+ }
}
}
(camel) 05/05: feat(component): MDC docs
Posted by pc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
pcongiusti pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
commit b5f0dda145585d617da1b6ac90a922b1573f5087
Author: Pasquale Congiusti <pa...@gmail.com>
AuthorDate: Thu Sep 25 14:44:57 2025 +0200
feat(component): MDC docs
---
.../main/camel-main-configuration-metadata.json | 3 +
.../org/apache/camel/catalog/others/mdc.json | 2 +-
components/camel-mdc/pom.xml | 2 +-
.../services/org/apache/camel/other.properties | 2 +-
.../camel-mdc/src/generated/resources/mdc.json | 2 +-
components/camel-mdc/src/main/docs/mdc.adoc | 59 ++++++++++++-
.../camel/mdc/MDCProcessorsInterceptStrategy.java | 63 ++++++++++----
.../main/java/org/apache/camel/mdc/MDCService.java | 3 +
.../java/org/apache/camel/mdc/MDCAsyncTest.java | 93 ++++++++------------
...{MDCAsyncTest.java => MDCAsyncWiretapTest.java} | 22 +++--
.../org/apache/camel/mdc/MyAsyncComponent.java | 46 ++++++++++
.../java/org/apache/camel/mdc/MyAsyncEndpoint.java | 98 ++++++++++++++++++++++
.../java/org/apache/camel/mdc/MyAsyncProducer.java | 75 +++++++++++++++++
.../camel-mdc/src/test/resources/log4j2.properties | 4 +-
.../main/MdcConfigurationPropertiesConfigurer.java | 32 ++++++-
.../camel-main-configuration-metadata.json | 3 +
core/camel-main/src/main/docs/main.adoc | 5 +-
.../org/apache/camel/main/BaseMainSupport.java | 2 +-
.../camel/main/MdcConfigurationProperties.java | 51 ++++++++++-
proposals/mdc.adoc | 8 +-
.../maven/packaging/PrepareCamelMainMojo.java | 2 +
21 files changed, 472 insertions(+), 105 deletions(-)
diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
index 6dbbe63d36a..fae5155bcac 100644
--- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
@@ -217,6 +217,9 @@
{ "name": "camel.management.uploadEnabled", "required": false, "description": "Whether to enable file upload via HTTP (not intended for production use). This functionality is for development to be able to reload Camel routes and code with source changes (if reload is enabled). If enabled then you can upload\/delete files via HTTP PUT\/DELETE on context-path: \/q\/upload\/{name}. You must also configure the uploadSourceDir option.", "sourceType": "org.apache.camel.main.HttpManagementS [...]
{ "name": "camel.management.uploadSourceDir", "required": false, "description": "Source directory when upload is enabled.", "sourceType": "org.apache.camel.main.HttpManagementServerConfigurationProperties", "type": "string", "javaType": "java.lang.String", "secret": false },
{ "name": "camel.management.useGlobalSslContextParameters", "required": false, "description": "Whether to use global SSL configuration for securing the embedded HTTP server.", "sourceType": "org.apache.camel.main.HttpManagementServerConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": false, "secret": false },
+ { "name": "camel.mdc.customExchangeHeaders", "required": false, "description": "Provide the headers you would like to use in the logging. Use * value to include all available headers", "sourceType": "org.apache.camel.main.MdcConfigurationProperties", "type": "string", "javaType": "java.lang.String", "secret": false },
+ { "name": "camel.mdc.customExchangeProperties", "required": false, "description": "Provide the properties you would like to use in the logging. Use * value to include all available properties", "sourceType": "org.apache.camel.main.MdcConfigurationProperties", "type": "string", "javaType": "java.lang.String", "secret": false },
+ { "name": "camel.mdc.enabled", "required": false, "description": "To enable MDC service", "sourceType": "org.apache.camel.main.MdcConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": false, "secret": false },
{ "name": "camel.metrics.baseEndpointURIExchangeEventNotifier", "required": false, "description": "Whether to use static or dynamic values for Endpoint Name tags in captured metrics. By default, static values are used. When using dynamic tags, then a dynamic to (toD) can compute many different endpoint URIs that, can lead to many tags as the URI is dynamic, so use this with care if setting this option to false.", "sourceType": "org.apache.camel.main.MetricsConfigurationProperties", " [...]
{ "name": "camel.metrics.binders", "required": false, "description": "Additional Micrometer binders to include such as jvm-memory, processor, jvm-thread, and so forth. Multiple binders can be separated by comma. The following binders currently is available from Micrometer: class-loader, commons-object-pool2, file-descriptor, hystrix-metrics-binder, jvm-compilation, jvm-gc, jvm-heap-pressure, jvm-info, jvm-memory, jvm-thread, log4j2, logback, processor, uptime", "sourceType": "org.apa [...]
{ "name": "camel.metrics.clearOnReload", "required": false, "description": "Clear the captured metrics data when Camel is reloading routes such as when using Camel JBang.", "sourceType": "org.apache.camel.main.MetricsConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": true, "secret": false },
diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json
index 073d9a5633d..47ba69df888 100644
--- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json
@@ -3,7 +3,7 @@
"kind": "other",
"name": "mdc",
"title": "Mdc",
- "description": "Mapped Diagnostic Context component",
+ "description": "Logging MDC (Mapped Diagnostic Context) Service",
"deprecated": false,
"firstVersion": "4.15.0",
"label": "logging",
diff --git a/components/camel-mdc/pom.xml b/components/camel-mdc/pom.xml
index 978c9d6892c..602ee335ab8 100644
--- a/components/camel-mdc/pom.xml
+++ b/components/camel-mdc/pom.xml
@@ -36,7 +36,7 @@
<artifactId>camel-mdc</artifactId>
<packaging>jar</packaging>
<name>Camel :: MDC</name>
- <description>Mapped Diagnostic Context component</description>
+ <description>Logging MDC (Mapped Diagnostic Context) Service</description>
<dependencies>
<dependency>
diff --git a/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties b/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties
index 2f66413827f..7862c26646d 100644
--- a/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties
+++ b/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties
@@ -4,4 +4,4 @@ groupId=org.apache.camel
artifactId=camel-mdc
version=4.15.0-SNAPSHOT
projectName=Camel :: MDC
-projectDescription=Mapped Diagnostic Context component
+projectDescription=Logging MDC (Mapped Diagnostic Context) Service
diff --git a/components/camel-mdc/src/generated/resources/mdc.json b/components/camel-mdc/src/generated/resources/mdc.json
index 073d9a5633d..47ba69df888 100644
--- a/components/camel-mdc/src/generated/resources/mdc.json
+++ b/components/camel-mdc/src/generated/resources/mdc.json
@@ -3,7 +3,7 @@
"kind": "other",
"name": "mdc",
"title": "Mdc",
- "description": "Mapped Diagnostic Context component",
+ "description": "Logging MDC (Mapped Diagnostic Context) Service",
"deprecated": false,
"firstVersion": "4.15.0",
"label": "logging",
diff --git a/components/camel-mdc/src/main/docs/mdc.adoc b/components/camel-mdc/src/main/docs/mdc.adoc
index 03ccd90ea33..b61f2af086c 100644
--- a/components/camel-mdc/src/main/docs/mdc.adoc
+++ b/components/camel-mdc/src/main/docs/mdc.adoc
@@ -2,9 +2,66 @@
:doctitle: Mdc
:shortname: mdc
:artifactid: camel-mdc
-:description: Mapped Diagnostic Context component
+:description: Logging MDC (Mapped Diagnostic Context) Service
:since: 4.15
:supportlevel: Preview
:tabs-sync-option:
*Since Camel {since}*
+
+This component is in charge to provide the configuration required to work with Mapped Diagnostic Context (MDC), a specification adopted by the major logging providers to add diagnostic information in the logging traces. Camel uses the API exposed by https://www.slf4j.org/manual.html#mdc[SLF4J logging facade]. The concrete implementation will depend on the logging system adopted.
+
+When you enable the MDC Service provided in this component, you will instruct your application to automatically store certain Camel Headers into the MDC storage. You can additionally provide more headers and properties through the component configuration. The MDC is normally sharing the storage per each thread. Given the multi threading nature of Camel, the component deals with the multithreading setting the information into the context and cleaning them once they have been used (general [...]
+
+== Usage
+
+If you want to use the feature, you need to include the `camel-mdc` dependency in your `pom.xml` and configure it with the parameters in the `application.properties` configuration file (at least set `camel.mdc.enabled=true`).
+
+The goal of this component is to avoid to work on low level API in Java. In older MDC implementations you had to hack into the code to include MDC such as:
+
+```java
+ org.slf4j.MDC.put("myCustomMDCKey", "myCustomKeyValue");
+```
+
+And later you had to make sure to provide MDC context propagation in async components (eg, `wiretap`) in order to make sure to have such context available in the new executing async thread. With this new service, the only thing to do is to add the value as a Camel Exchange header (or a property), for example:
+
+```java
+ .setHeader("myCustomMDCKey", simple("myCustomKeyValue"))
+```
+include the MDC service and additionally instruct the Camel application to treat that header as a MDC trace (via `camel.mdc.customHeaders=myCustomMDCKey` or `*` to include all headers). You won't need any longer to worry about context propagation as the propagation will be done via Camel Exchange instead.
+
+NOTE: you won't also need any longer to hack the code using Java DSL, as you can put headers in any Camel DSL.
+
+Depending on the logging technology used, you can now include the MDC parameters you want to trace in your logging configuration. For example, in `log4j2` configuration you can include them as shown below:
+
+```
+... [%X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{customHead}, %X{customProp}]
+```
+
+During the execution you can verify the output of the log to see the traces appended to your logger.
+
+== Default headers
+
+This is the list of default MDC values included in each execution:
+
+* camel.breadcrumbId
+* camel.exchangeId
+* camel.messageId
+* camel.correlationId
+* camel.routeId
+* camel.contextId
+* camel.threadId
+
+If they exists in the Exchange, then, they will be included in the MDC. You can use `camel.mdc.customHeaders` and `camel.mdc.customProperties` to include any further header and property you need to trace.
+
+== Configuration
+
+The configuration properties for the MDC component are:
+
+[width="100%",cols="10%,10%,80%",options="header",]
+|=======================================================================
+|Option |Default |Description
+|`camel.mdc.enabled`| false | Enable the MDC logging.
+|`camel.mdc.customHeaders` | | Provide the headers you would like to use in the logging. Use `*` value to include all available headers.
+|`camel.mdc.customProperties` | | Provide the properties you would like to use in the logging. Use `*` value to include all available properties.
+|=======================================================================
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java
index 3306a40e90d..02c755f8401 100644
--- a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCProcessorsInterceptStrategy.java
@@ -16,12 +16,16 @@
*/
package org.apache.camel.mdc;
+import java.util.concurrent.CompletableFuture;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.AsyncProcessor;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.NamedNode;
import org.apache.camel.Processor;
import org.apache.camel.spi.InterceptStrategy;
-import org.apache.camel.support.processor.DelegateAsyncProcessor;
+import org.apache.camel.support.AsyncProcessorConverterHelper;
/**
* MDCProcessorsInterceptStrategy is used to wrap each processor calls and generate the MDC context for each process
@@ -37,28 +41,51 @@ public class MDCProcessorsInterceptStrategy implements InterceptStrategy {
@Override
public Processor wrapProcessorInInterceptors(
- CamelContext camelContext,
- NamedNode processorDefinition, Processor target, Processor nextTarget)
+ final CamelContext context,
+ final NamedNode definition,
+ final Processor target,
+ final Processor nextTarget)
throws Exception {
- return new DelegateAsyncProcessor(new TraceProcessor(target));
- }
- private class TraceProcessor implements Processor {
- private final Processor target;
+ final AsyncProcessor asyncProcessor = AsyncProcessorConverterHelper.convert(target);
+
+ return new AsyncProcessor() {
+
+ @Override
+ public boolean process(Exchange exchange, AsyncCallback callback) {
+ mdcService.setMDC(exchange);
+ return asyncProcessor.process(exchange, doneSync -> {
+ mdcService.unsetMDC();
+ callback.done(doneSync);
+ });
+ }
+
+ @Override
+ public void process(Exchange exchange) throws Exception {
+ mdcService.setMDC(exchange);
+ try {
+ asyncProcessor.process(exchange);
+ } finally {
+ mdcService.unsetMDC();
+ }
+ }
- public TraceProcessor(Processor target) {
- this.target = target;
- }
+ @Override
+ public CompletableFuture<Exchange> processAsync(Exchange exchange) {
+ CompletableFuture<Exchange> future = new CompletableFuture<>();
+ mdcService.setMDC(exchange);
+ asyncProcessor.process(exchange, doneSync -> {
+ if (exchange.getException() != null) {
+ future.completeExceptionally(exchange.getException());
+ } else {
+ future.complete(exchange);
+ }
+ mdcService.unsetMDC();
+ });
- @Override
- public void process(Exchange exchange) throws Exception {
- mdcService.setMDC(exchange);
- try {
- target.process(exchange);
- } finally {
- mdcService.unsetMDC();
+ return future;
}
- }
+ };
}
}
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
index 5ac3a429881..47191e79586 100644
--- a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
@@ -39,6 +39,7 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
static String MDC_MESSAGE_ID = "camel.messageId";
static String MDC_CORRELATION_ID = "camel.correlationId";
static String MDC_ROUTE_ID = "camel.routeId";
+ static String MDC_CAMEL_THREAD_ID = "camel.threadId";
static String MDC_CAMEL_CONTEXT_ID = "camel.contextId";
private static final Logger LOG = LoggerFactory.getLogger(MDCService.class);
@@ -149,6 +150,8 @@ public class MDCService extends ServiceSupport implements CamelMDCService {
MDC.put(MDC_EXCHANGE_ID, exchange.getExchangeId());
MDC.put(MDC_MESSAGE_ID, exchange.getMessage().getMessageId());
MDC.put(MDC_CAMEL_CONTEXT_ID, exchange.getContext().getName());
+ // Useful to make sure aync execution is properly propagating context
+ MDC.put(MDC_CAMEL_THREAD_ID, Thread.currentThread().getName());
// Backward compatibility: this info may not be longer widely used
String corrId = exchange.getProperty(ExchangePropertyKey.CORRELATION_ID, String.class);
if (corrId != null) {
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
index 7a5c2284a1d..5b94104bf3f 100644
--- a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
@@ -16,28 +16,21 @@
*/
package org.apache.camel.mdc;
-import java.io.IOException;
-
import org.apache.camel.CamelContext;
import org.apache.camel.CamelContextAware;
-import org.apache.camel.RoutesBuilder;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.ExchangeTestSupport;
import org.junit.jupiter.api.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class MDCAsyncTest extends ExchangeTestSupport {
- private static final Logger LOG = LoggerFactory.getLogger(MDCAsyncTest.class);
-
@Override
protected CamelContext createCamelContext() throws Exception {
MDCService mdcSvc = new MDCService();
@@ -50,69 +43,49 @@ public class MDCAsyncTest extends ExchangeTestSupport {
}
@Test
- void testRouteSingleRequest() throws IOException, InterruptedException {
- MockEndpoint mock = getMockEndpoint("mock:end");
- mock.expectedMessageCount(1);
- mock.setAssertPeriod(5000);
- context.createProducerTemplate().sendBody("direct:start", null);
- mock.assertIsSatisfied(1000);
- // We should get no MDC after the route has been executed
- assertEquals(0, MDC.getCopyOfContextMap().size());
+ public void testAsyncEndpoint() throws Exception {
+ getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel");
+ getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel");
+ getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel");
+
+ String reply = template.requestBody("direct:start", "Hello Camel", String.class);
+ assertEquals("Bye Camel", reply);
}
@Override
- protected RoutesBuilder createRouteBuilder() {
+ protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
- from("direct:start")
- .setBody()
- .simple("start")
- .log("start: ${exchangeId}")
- .to("direct:a")
- .wireTap("direct:b");
+ context.addComponent("async", new MyAsyncComponent());
- from("direct:a")
+ from("direct:start").to("mock:before").to("log:before")
.setProperty("prop1", simple("Property1"))
.setHeader("head", simple("Header1"))
- .process(exchange -> {
- LOG.info("Direct:a process");
- assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
- assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
- assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
- assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
- assertEquals("Header1", MDC.get("head"));
- assertEquals("Property1", MDC.get("prop1"));
- assertNull(MDC.get("prop2"));
- // We store the exchange of this execution in a property
- // as we will use this property to evaluate the exchange in the direct:b execution
- exchange.setProperty("directa-exchange", exchange.getExchangeId());
- })
- .setBody()
- .simple("Direct a")
- .log("directa: ${exchangeId}");
+ .process(new Processor() {
+ public void process(Exchange exchange) {
+ assertEquals("Header1", MDC.get("head"));
+ assertEquals("Property1", MDC.get("prop1"));
+ assertNull(MDC.get("prop2"));
+ // We store the threadId of this execution in a property
+ // as we will use it to assert the thread is different in the direct:b execution
+ exchange.setProperty("thread-a", MDC.get(MDCService.MDC_CAMEL_THREAD_ID));
+ }
+ }).recipientList(constant("direct:foo"));
- from("direct:b")
+ from("direct:foo").to("async:bye:camel")
.setProperty("prop2", simple("Property2"))
.setHeader("head", simple("Header2"))
- .process(exchange -> {
- LOG.info("Direct:b process");
- assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
- assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
- assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
- assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
- assertEquals("Header2", MDC.get("head"));
- // NOTE: properties are shared
- assertEquals("Property1", MDC.get("prop1"));
- assertEquals("Property2", MDC.get("prop2"));
- // We use as support storage the same properties
- assertNotEquals(exchange.getProperty("directa-exchange"), MDC.get(MDCService.MDC_EXCHANGE_ID));
- })
- .delay(2000)
- .setBody()
- .simple("Direct b")
- .log("directb: ${exchangeId}")
- .to("mock:end");
+ .process(new Processor() {
+ public void process(Exchange exchange) {
+ // Make sure this execution is spanned in a different thread
+ // but still the context (in this case the properties) is propagated
+ assertNotEquals(exchange.getProperty("thread-a"), MDC.get(MDCService.MDC_CAMEL_THREAD_ID));
+ assertEquals("Header2", MDC.get("head"));
+ assertEquals("Property1", MDC.get("prop1"));
+ assertEquals("Property2", MDC.get("prop2"));
+ }
+ }).to("log:after").to("mock:after").to("mock:result");
}
};
}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncWiretapTest.java
similarity index 85%
copy from components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
copy to components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncWiretapTest.java
index 7a5c2284a1d..f549a830dd9 100644
--- a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncTest.java
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MDCAsyncWiretapTest.java
@@ -34,9 +34,9 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-public class MDCAsyncTest extends ExchangeTestSupport {
+public class MDCAsyncWiretapTest extends ExchangeTestSupport {
- private static final Logger LOG = LoggerFactory.getLogger(MDCAsyncTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(MDCAsyncWiretapTest.class);
@Override
protected CamelContext createCamelContext() throws Exception {
@@ -70,6 +70,7 @@ public class MDCAsyncTest extends ExchangeTestSupport {
.simple("start")
.log("start: ${exchangeId}")
.to("direct:a")
+ // MUST be any async component
.wireTap("direct:b");
from("direct:a")
@@ -81,12 +82,13 @@ public class MDCAsyncTest extends ExchangeTestSupport {
assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ assertNotNull(MDC.get(MDCService.MDC_CAMEL_THREAD_ID));
assertEquals("Header1", MDC.get("head"));
assertEquals("Property1", MDC.get("prop1"));
assertNull(MDC.get("prop2"));
- // We store the exchange of this execution in a property
- // as we will use this property to evaluate the exchange in the direct:b execution
- exchange.setProperty("directa-exchange", exchange.getExchangeId());
+ // We store the threadId of this execution in a property
+ // as we will use it to assert the thread is different in the direct:b execution
+ exchange.setProperty("thread-a", MDC.get(MDCService.MDC_CAMEL_THREAD_ID));
})
.setBody()
.simple("Direct a")
@@ -97,16 +99,12 @@ public class MDCAsyncTest extends ExchangeTestSupport {
.setHeader("head", simple("Header2"))
.process(exchange -> {
LOG.info("Direct:b process");
- assertNotNull(MDC.get(MDCService.MDC_MESSAGE_ID));
- assertNotNull(MDC.get(MDCService.MDC_EXCHANGE_ID));
- assertNotNull(MDC.get(MDCService.MDC_ROUTE_ID));
- assertNotNull(MDC.get(MDCService.MDC_CAMEL_CONTEXT_ID));
+ // Make sure this execution is spanned in a different thread
+ // but still the context (in this case the properties) is propagated
+ assertNotEquals(exchange.getProperty("thread-a"), MDC.get(MDCService.MDC_CAMEL_THREAD_ID));
assertEquals("Header2", MDC.get("head"));
- // NOTE: properties are shared
assertEquals("Property1", MDC.get("prop1"));
assertEquals("Property2", MDC.get("prop2"));
- // We use as support storage the same properties
- assertNotEquals(exchange.getProperty("directa-exchange"), MDC.get(MDCService.MDC_EXCHANGE_ID));
})
.delay(2000)
.setBody()
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncComponent.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncComponent.java
new file mode 100644
index 00000000000..141a3041a0c
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncComponent.java
@@ -0,0 +1,46 @@
+/*
+ * 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.mdc;
+
+import java.util.Map;
+
+import org.apache.camel.Endpoint;
+import org.apache.camel.support.DefaultComponent;
+import org.apache.camel.util.StringHelper;
+
+public class MyAsyncComponent extends DefaultComponent {
+
+ @Override
+ protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
+ MyAsyncEndpoint answer = new MyAsyncEndpoint(uri, this);
+ answer.setReply(prepareReply(remaining));
+ setProperties(answer, parameters);
+ return answer;
+ }
+
+ private String prepareReply(String value) {
+ // to make URIs valid we make the conventions of using ':' for ' ' and
+ // capitalize words
+ String[] words = value.split(":");
+ StringBuilder result = new StringBuilder();
+ for (String word : words) {
+ result.append(result.isEmpty() ? "" : " ");
+ result.append(StringHelper.capitalize(word));
+ }
+ return result.toString();
+ }
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncEndpoint.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncEndpoint.java
new file mode 100644
index 00000000000..71f0474e112
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncEndpoint.java
@@ -0,0 +1,98 @@
+/*
+ * 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.mdc;
+
+import org.apache.camel.Component;
+import org.apache.camel.Consumer;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.support.SynchronousDelegateProducer;
+
+public class MyAsyncEndpoint extends DefaultEndpoint {
+
+ private boolean append;
+ private String reply;
+ private long delay = 25;
+ private int failFirstAttempts;
+ private boolean synchronous;
+
+ public MyAsyncEndpoint(String endpointUri, Component component) {
+ super(endpointUri, component);
+ }
+
+ @Override
+ public Producer createProducer() {
+ Producer answer = new MyAsyncProducer(this);
+ if (isSynchronous()) {
+ // force it to be synchronously
+ return new SynchronousDelegateProducer(answer);
+ } else {
+ return answer;
+ }
+ }
+
+ @Override
+ public Consumer createConsumer(Processor processor) {
+ throw new UnsupportedOperationException("Consumer not supported");
+ }
+
+ @Override
+ public boolean isSingleton() {
+ return true;
+ }
+
+ public boolean isSynchronous() {
+ return synchronous;
+ }
+
+ public void setSynchronous(boolean synchronous) {
+ this.synchronous = synchronous;
+ }
+
+ public String getReply() {
+ return reply;
+ }
+
+ public void setReply(String reply) {
+ this.reply = reply;
+ }
+
+ public long getDelay() {
+ return delay;
+ }
+
+ public void setDelay(long delay) {
+ this.delay = delay;
+ }
+
+ public int getFailFirstAttempts() {
+ return failFirstAttempts;
+ }
+
+ public void setFailFirstAttempts(int failFirstAttempts) {
+ this.failFirstAttempts = failFirstAttempts;
+ }
+
+ public boolean isAppend() {
+ return append;
+ }
+
+ public void setAppend(boolean append) {
+ this.append = append;
+ }
+}
diff --git a/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncProducer.java b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncProducer.java
new file mode 100644
index 00000000000..4e99a798a4c
--- /dev/null
+++ b/components/camel-mdc/src/test/java/org/apache/camel/mdc/MyAsyncProducer.java
@@ -0,0 +1,75 @@
+/*
+ * 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.mdc;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.CamelExchangeException;
+import org.apache.camel.Exchange;
+import org.apache.camel.support.DefaultAsyncProducer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class MyAsyncProducer extends DefaultAsyncProducer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MyAsyncProducer.class);
+ private final ExecutorService executor;
+ private final AtomicInteger counter = new AtomicInteger();
+
+ public MyAsyncProducer(MyAsyncEndpoint endpoint) {
+ super(endpoint);
+ this.executor = endpoint.getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, "MyProducer");
+ }
+
+ @Override
+ public MyAsyncEndpoint getEndpoint() {
+ return (MyAsyncEndpoint) super.getEndpoint();
+ }
+
+ @Override
+ public boolean process(final Exchange exchange, final AsyncCallback callback) {
+ executor.submit(new Callable<Object>() {
+ public Object call() throws Exception {
+ LOG.info("Simulating a task which takes {} millis to reply", getEndpoint().getDelay());
+ Thread.sleep(getEndpoint().getDelay());
+
+ int count = counter.incrementAndGet();
+ if (getEndpoint().getFailFirstAttempts() >= count) {
+ LOG.info("Simulating a failure at attempt {}", count);
+ exchange.setException(new CamelExchangeException("Simulated error at attempt " + count, exchange));
+ } else {
+ String reply = getEndpoint().getReply();
+ reply = getEndpoint().isAppend() ? exchange.getIn().getBody() + " " + reply : reply;
+ exchange.getMessage().setBody(reply);
+ LOG.info("Setting reply {}", reply);
+ }
+
+ LOG.info("Callback done(false)");
+ callback.done(false);
+ return null;
+ }
+ });
+
+ // indicate from this point forward its being routed asynchronously
+ LOG.info("Task submitted, now tell Camel routing engine to that this Exchange is being continued asynchronously");
+ return false;
+ }
+
+}
diff --git a/components/camel-mdc/src/test/resources/log4j2.properties b/components/camel-mdc/src/test/resources/log4j2.properties
index 590933e3e26..731b4840a10 100644
--- a/components/camel-mdc/src/test/resources/log4j2.properties
+++ b/components/camel-mdc/src/test/resources/log4j2.properties
@@ -17,14 +17,14 @@
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
-appender.console.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m [%X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{head1}, %X{prop1}, %X{head2}, %X{prop2}]%n
+appender.console.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m [%X{camel.threadId}, %X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{head1}, %X{prop1}, %X{head2}, %X{prop2}]%n
appender.file.type = File
appender.file.name = file
appender.file.fileName = target/camel-mdc-test.log
appender.file.append = true
appender.file.layout.type = PatternLayout
-appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m [%X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{head1}, %X{prop1}, %X{head2}, %X{prop2}]%n
+appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m [%X{camel.threadId}, %X{camel.contextId}, %X{camel.routeId}, %X{camel.exchangeId}, %X{camel.messageId}, %X{head1}, %X{prop1}, %X{head2}, %X{prop2}]%n
rootLogger.level = INFO
rootLogger.appenderRef.file.ref = file
diff --git a/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java b/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java
index 9707c284526..abc3e624f75 100644
--- a/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java
+++ b/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java
@@ -22,12 +22,23 @@ public class MdcConfigurationPropertiesConfigurer extends org.apache.camel.suppo
private static final Map<String, Object> ALL_OPTIONS;
static {
Map<String, Object> map = new CaseInsensitiveMap();
+ map.put("CustomExchangeHeaders", java.lang.String.class);
+ map.put("CustomExchangeProperties", java.lang.String.class);
+ map.put("Enabled", boolean.class);
ALL_OPTIONS = map;
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
- return false;
+ org.apache.camel.main.MdcConfigurationProperties target = (org.apache.camel.main.MdcConfigurationProperties) obj;
+ switch (ignoreCase ? name.toLowerCase() : name) {
+ case "customexchangeheaders":
+ case "customExchangeHeaders": target.setCustomExchangeHeaders(property(camelContext, java.lang.String.class, value)); return true;
+ case "customexchangeproperties":
+ case "customExchangeProperties": target.setCustomExchangeProperties(property(camelContext, java.lang.String.class, value)); return true;
+ case "enabled": target.setEnabled(property(camelContext, boolean.class, value)); return true;
+ default: return false;
+ }
}
@Override
@@ -37,12 +48,27 @@ public class MdcConfigurationPropertiesConfigurer extends org.apache.camel.suppo
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
- return null;
+ switch (ignoreCase ? name.toLowerCase() : name) {
+ case "customexchangeheaders":
+ case "customExchangeHeaders": return java.lang.String.class;
+ case "customexchangeproperties":
+ case "customExchangeProperties": return java.lang.String.class;
+ case "enabled": return boolean.class;
+ default: return null;
+ }
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
- return null;
+ org.apache.camel.main.MdcConfigurationProperties target = (org.apache.camel.main.MdcConfigurationProperties) obj;
+ switch (ignoreCase ? name.toLowerCase() : name) {
+ case "customexchangeheaders":
+ case "customExchangeHeaders": return target.getCustomExchangeHeaders();
+ case "customexchangeproperties":
+ case "customExchangeProperties": return target.getCustomExchangeProperties();
+ case "enabled": return target.isEnabled();
+ default: return null;
+ }
}
}
diff --git a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
index 6dbbe63d36a..fae5155bcac 100644
--- a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
+++ b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
@@ -217,6 +217,9 @@
{ "name": "camel.management.uploadEnabled", "required": false, "description": "Whether to enable file upload via HTTP (not intended for production use). This functionality is for development to be able to reload Camel routes and code with source changes (if reload is enabled). If enabled then you can upload\/delete files via HTTP PUT\/DELETE on context-path: \/q\/upload\/{name}. You must also configure the uploadSourceDir option.", "sourceType": "org.apache.camel.main.HttpManagementS [...]
{ "name": "camel.management.uploadSourceDir", "required": false, "description": "Source directory when upload is enabled.", "sourceType": "org.apache.camel.main.HttpManagementServerConfigurationProperties", "type": "string", "javaType": "java.lang.String", "secret": false },
{ "name": "camel.management.useGlobalSslContextParameters", "required": false, "description": "Whether to use global SSL configuration for securing the embedded HTTP server.", "sourceType": "org.apache.camel.main.HttpManagementServerConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": false, "secret": false },
+ { "name": "camel.mdc.customExchangeHeaders", "required": false, "description": "Provide the headers you would like to use in the logging. Use * value to include all available headers", "sourceType": "org.apache.camel.main.MdcConfigurationProperties", "type": "string", "javaType": "java.lang.String", "secret": false },
+ { "name": "camel.mdc.customExchangeProperties", "required": false, "description": "Provide the properties you would like to use in the logging. Use * value to include all available properties", "sourceType": "org.apache.camel.main.MdcConfigurationProperties", "type": "string", "javaType": "java.lang.String", "secret": false },
+ { "name": "camel.mdc.enabled", "required": false, "description": "To enable MDC service", "sourceType": "org.apache.camel.main.MdcConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": false, "secret": false },
{ "name": "camel.metrics.baseEndpointURIExchangeEventNotifier", "required": false, "description": "Whether to use static or dynamic values for Endpoint Name tags in captured metrics. By default, static values are used. When using dynamic tags, then a dynamic to (toD) can compute many different endpoint URIs that, can lead to many tags as the URI is dynamic, so use this with care if setting this option to false.", "sourceType": "org.apache.camel.main.MetricsConfigurationProperties", " [...]
{ "name": "camel.metrics.binders", "required": false, "description": "Additional Micrometer binders to include such as jvm-memory, processor, jvm-thread, and so forth. Multiple binders can be separated by comma. The following binders currently is available from Micrometer: class-loader, commons-object-pool2, file-descriptor, hystrix-metrics-binder, jvm-compilation, jvm-gc, jvm-heap-pressure, jvm-info, jvm-memory, jvm-thread, log4j2, logback, processor, uptime", "sourceType": "org.apa [...]
{ "name": "camel.metrics.clearOnReload", "required": false, "description": "Clear the captured metrics data when Camel is reloading routes such as when using Camel JBang.", "sourceType": "org.apache.camel.main.MetricsConfigurationProperties", "type": "boolean", "javaType": "boolean", "defaultValue": true, "secret": false },
diff --git a/core/camel-main/src/main/docs/main.adoc b/core/camel-main/src/main/docs/main.adoc
index 78a79e8b33a..c922a5d7d95 100644
--- a/core/camel-main/src/main/docs/main.adoc
+++ b/core/camel-main/src/main/docs/main.adoc
@@ -563,11 +563,14 @@ The camel.telemetryDev supports 4 options, which are listed below.
=== Camel MDC configurations
-The camel.mdc supports 0 options, which are listed below.
+The camel.mdc supports 3 options, which are listed below.
[width="100%",cols="2,5,^1,2",options="header"]
|===
| Name | Description | Default | Type
+| *camel.mdc.customExchange{zwsp}Headers* | Provide the headers you would like to use in the logging. Use * value to include all available headers | | String
+| *camel.mdc.customExchange{zwsp}Properties* | Provide the properties you would like to use in the logging. Use * value to include all available properties | | String
+| *camel.mdc.enabled* | To enable MDC service | false | boolean
|===
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
index 84e69be5b48..b7857dd07d9 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
@@ -2790,7 +2790,7 @@ public abstract class BaseMainSupport extends BaseService {
answer = camelContext.getCamelContextExtension().getBootstrapFactoryFinder()
.newInstance("mdc-service", CamelMDCService.class)
.orElseThrow(() -> new IllegalArgumentException(
- "Cannot find OpenTelemetryTracer2 on classpath. Add camel-opentelemetry2 to classpath."));
+ "Cannot find CamelMDCService on classpath. Add camel-mdc to classpath."));
}
return answer;
}
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java b/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java
index 4d678032669..1d570b320fb 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java
@@ -28,6 +28,8 @@ public class MdcConfigurationProperties implements BootstrapCloseable {
private MainConfigurationProperties parent;
private boolean enabled;
+ private String customExchangeHeaders;
+ private String customExchangeProperties;
public MdcConfigurationProperties(MainConfigurationProperties parent) {
this.parent = parent;
@@ -47,11 +49,58 @@ public class MdcConfigurationProperties implements BootstrapCloseable {
}
/**
- * To enable Mdc
+ * To enable MDC service
+ */
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ public String getCustomExchangeHeaders() {
+ return customExchangeHeaders;
+ }
+
+ /**
+ * Provide the headers you would like to use in the logging. Use `*` value to include all available headers
+ */
+ public void setCustomExchangeHeaders(String customExchangeHeaders) {
+ this.customExchangeHeaders = customExchangeHeaders;
+ }
+
+ public String getCustomExchangeProperties() {
+ return customExchangeProperties;
+ }
+
+ /**
+ * Provide the properties you would like to use in the logging. Use `*` value to include all available
+ * properties
+ */
+ public void setCustomExchangeProperties(String customExchangeProperties) {
+ this.customExchangeProperties = customExchangeProperties;
+ }
+
+ /**
+ * To enable MDC service
*/
public MdcConfigurationProperties withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
+ /**
+ * Provide the headers you would like to use in the logging. Use `*` value to include all available headers
+ */
+ public MdcConfigurationProperties withCustomExchangeHeaders(String customExchangeHeaders) {
+ this.customExchangeHeaders = customExchangeHeaders;
+ return this;
+ }
+
+ /**
+ * Provide the properties you would like to use in the logging. Use `*` value to include all available
+ * properties
+ */
+ public MdcConfigurationProperties withCustomExchangeProperties(String customExchangeProperties) {
+ this.customExchangeProperties = customExchangeProperties;
+ return this;
+ }
+
}
diff --git a/proposals/mdc.adoc b/proposals/mdc.adoc
index a65c8fd6655..4fb883afbe9 100644
--- a/proposals/mdc.adoc
+++ b/proposals/mdc.adoc
@@ -5,8 +5,8 @@ authors:
reviewers: ["@davsclaus"]
approvers: ["@davsclaus"]
creation-date: 2025-03-07
-last-updated: 2025-03-21
-status: implementable
+last-updated: 2025-09-25
+status: implemented
see-also: []
replaces: []
superseded-by: []
@@ -93,3 +93,7 @@ If the above is proven to work effectively, then, in any future major version we
== Development
This design proposals should not introduce any breaking compatibility changes. The old and new MDC mechanism can coexist, although it will be recommendable to deprecate the old one once the new one proves to work correctly.
+
+=== `camel-mdc` component (2025-09-25)
+
+Developed a component which cover the design specifications. See component documentation for more details.
\ No newline at end of file
diff --git a/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java b/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java
index 324dd3d4176..39bff690a96 100644
--- a/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java
+++ b/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java
@@ -233,6 +233,8 @@ public class PrepareCamelMainMojo extends AbstractGeneratorMojo {
prefix = "camel.opentelemetry.";
} else if (file.getName().contains("TelemetryDev")) {
prefix = "camel.telemetryDev.";
+ } else if (file.getName().contains("MdcConfigurationProperties")) {
+ prefix = "camel.mdc.";
} else if (file.getName().contains("Metrics")) {
prefix = "camel.metrics.";
} else if (file.getName().contains("HttpServer")) {
(camel) 01/05: feat(components): Camel MDC
Posted by pc...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
pcongiusti pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
commit 04fece586e1baeecba6dfd98ab7182ed40768df8
Author: Pasquale Congiusti <pa...@gmail.com>
AuthorDate: Tue Sep 23 16:05:11 2025 +0200
feat(components): Camel MDC
---
bom/camel-bom/pom.xml | 5 ++
catalog/camel-allcomponents/pom.xml | 5 ++
.../main/camel-main-configuration-metadata.json | 1 +
.../org/apache/camel/catalog/others.properties | 1 +
.../org/apache/camel/catalog/others/mdc.json | 15 ++++
components/camel-mdc/pom.xml | 63 +++++++++++++++
.../META-INF/services/org/apache/camel/mdc-service | 2 +
.../services/org/apache/camel/other.properties | 7 ++
.../camel-mdc/src/generated/resources/mdc.json | 15 ++++
components/camel-mdc/src/main/docs/mdc.adoc | 10 +++
.../main/java/org/apache/camel/mdc/MDCService.java | 89 ++++++++++++++++++++++
.../camel-mdc/src/test/resources/log4j2.properties | 30 ++++++++
components/pom.xml | 1 +
.../java/org/apache/camel/spi/CamelMDCService.java | 27 +++++++
.../java/org/apache/camel/spi/LogListener.java | 12 +++
.../org/apache/camel/processor/LogProcessor.java | 20 +++++
.../main/MdcConfigurationPropertiesConfigurer.java | 48 ++++++++++++
.../camel-main-configuration-metadata.json | 1 +
...rg.apache.camel.main.MdcConfigurationProperties | 2 +
core/camel-main/src/main/docs/main.adoc | 9 +++
.../org/apache/camel/main/BaseMainSupport.java | 56 +++++++++++++-
.../camel/main/MainConfigurationProperties.java | 12 +++
.../camel/main/MdcConfigurationProperties.java | 57 ++++++++++++++
.../camel/support/processor/CamelLogProcessor.java | 22 ++++++
.../modules/others/examples/json/mdc.json | 1 +
docs/components/modules/others/nav.adoc | 1 +
docs/components/modules/others/pages/mdc.adoc | 1 +
parent/pom.xml | 5 ++
.../maven/packaging/PrepareCamelMainMojo.java | 3 +
29 files changed, 520 insertions(+), 1 deletion(-)
diff --git a/bom/camel-bom/pom.xml b/bom/camel-bom/pom.xml
index 7e3bf987964..fa912d0b1b2 100644
--- a/bom/camel-bom/pom.xml
+++ b/bom/camel-bom/pom.xml
@@ -1477,6 +1477,11 @@
<artifactId>camel-master</artifactId>
<version>4.15.0-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-mdc</artifactId>
+ <version>4.15.0-SNAPSHOT</version>
+ </dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-metrics</artifactId>
diff --git a/catalog/camel-allcomponents/pom.xml b/catalog/camel-allcomponents/pom.xml
index dbe1e7a85fd..2b96ba6ae96 100644
--- a/catalog/camel-allcomponents/pom.xml
+++ b/catalog/camel-allcomponents/pom.xml
@@ -1286,6 +1286,11 @@
<artifactId>camel-master</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-mdc</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-metrics</artifactId>
diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
index bb1e632f40c..6dbbe63d36a 100644
--- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/main/camel-main-configuration-metadata.json
@@ -21,6 +21,7 @@
{ "name": "camel.opentelemetry", "description": "Camel OpenTelemetry configurations", "sourceType": "org.apache.camel.main.OtelConfigurationProperties" },
{ "name": "camel.opentelemetry2", "description": "Camel OpenTelemetry 2 configurations", "sourceType": "org.apache.camel.main.Otel2ConfigurationProperties" },
{ "name": "camel.telemetryDev", "description": "Camel Telemetry Dev configurations", "sourceType": "org.apache.camel.main.TelemetryDevConfigurationProperties" },
+ { "name": "camel.mdc", "description": "Camel MDC configurations", "sourceType": "org.apache.camel.main.MdcConfigurationProperties" },
{ "name": "camel.metrics", "description": "Camel Micrometer Metrics configurations", "sourceType": "org.apache.camel.main.MetricsConfigurationProperties" },
{ "name": "camel.faulttolerance", "description": "Fault Tolerance EIP Circuit Breaker configurations", "sourceType": "org.apache.camel.main.FaultToleranceConfigurationProperties" },
{ "name": "camel.resilience4j", "description": "Resilience4j EIP Circuit Breaker configurations", "sourceType": "org.apache.camel.main.Resilience4jConfigurationProperties" },
diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others.properties b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others.properties
index 39b1e80ca2e..bbd73f057a6 100644
--- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others.properties
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others.properties
@@ -26,6 +26,7 @@ lra
mail-microsoft-oauth
main
management
+mdc
micrometer-observability
micrometer-prometheus
microprofile-config
diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json
new file mode 100644
index 00000000000..073d9a5633d
--- /dev/null
+++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/others/mdc.json
@@ -0,0 +1,15 @@
+{
+ "other": {
+ "kind": "other",
+ "name": "mdc",
+ "title": "Mdc",
+ "description": "Mapped Diagnostic Context component",
+ "deprecated": false,
+ "firstVersion": "4.15.0",
+ "label": "logging",
+ "supportLevel": "Preview",
+ "groupId": "org.apache.camel",
+ "artifactId": "camel-mdc",
+ "version": "4.15.0-SNAPSHOT"
+ }
+}
diff --git a/components/camel-mdc/pom.xml b/components/camel-mdc/pom.xml
new file mode 100644
index 00000000000..978c9d6892c
--- /dev/null
+++ b/components/camel-mdc/pom.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>components</artifactId>
+ <version>4.15.0-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <firstVersion>4.15.0</firstVersion>
+ <label>logging</label>
+ <supportLevel>Preview</supportLevel>
+ </properties>
+
+ <artifactId>camel-mdc</artifactId>
+ <packaging>jar</packaging>
+ <name>Camel :: MDC</name>
+ <description>Mapped Diagnostic Context component</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-support</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-test-spring-junit5</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>${mockito-version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+</project>
diff --git a/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/mdc-service b/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/mdc-service
new file mode 100644
index 00000000000..cdc20a7cf74
--- /dev/null
+++ b/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/mdc-service
@@ -0,0 +1,2 @@
+# Generated by camel build tools - do NOT edit this file!
+class=org.apache.camel.mdc.MDCService
diff --git a/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties b/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties
new file mode 100644
index 00000000000..2f66413827f
--- /dev/null
+++ b/components/camel-mdc/src/generated/resources/META-INF/services/org/apache/camel/other.properties
@@ -0,0 +1,7 @@
+# Generated by camel build tools - do NOT edit this file!
+name=mdc
+groupId=org.apache.camel
+artifactId=camel-mdc
+version=4.15.0-SNAPSHOT
+projectName=Camel :: MDC
+projectDescription=Mapped Diagnostic Context component
diff --git a/components/camel-mdc/src/generated/resources/mdc.json b/components/camel-mdc/src/generated/resources/mdc.json
new file mode 100644
index 00000000000..073d9a5633d
--- /dev/null
+++ b/components/camel-mdc/src/generated/resources/mdc.json
@@ -0,0 +1,15 @@
+{
+ "other": {
+ "kind": "other",
+ "name": "mdc",
+ "title": "Mdc",
+ "description": "Mapped Diagnostic Context component",
+ "deprecated": false,
+ "firstVersion": "4.15.0",
+ "label": "logging",
+ "supportLevel": "Preview",
+ "groupId": "org.apache.camel",
+ "artifactId": "camel-mdc",
+ "version": "4.15.0-SNAPSHOT"
+ }
+}
diff --git a/components/camel-mdc/src/main/docs/mdc.adoc b/components/camel-mdc/src/main/docs/mdc.adoc
new file mode 100644
index 00000000000..03ccd90ea33
--- /dev/null
+++ b/components/camel-mdc/src/main/docs/mdc.adoc
@@ -0,0 +1,10 @@
+= Mdc Component
+:doctitle: Mdc
+:shortname: mdc
+:artifactid: camel-mdc
+:description: Mapped Diagnostic Context component
+:since: 4.15
+:supportlevel: Preview
+:tabs-sync-option:
+
+*Since Camel {since}*
diff --git a/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
new file mode 100644
index 00000000000..098230b11a0
--- /dev/null
+++ b/components/camel-mdc/src/main/java/org/apache/camel/mdc/MDCService.java
@@ -0,0 +1,89 @@
+/*
+ * 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.mdc;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.spi.CamelLogger;
+import org.apache.camel.spi.CamelMDCService;
+import org.apache.camel.spi.LogListener;
+import org.apache.camel.spi.annotations.JdkService;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+@JdkService("mdc-service")
+public class MDCService extends ServiceSupport implements CamelMDCService {
+
+ private static final Logger LOG = LoggerFactory.getLogger(MDCService.class);
+
+ private CamelContext camelContext;
+
+ @Override
+ public CamelContext getCamelContext() {
+ return camelContext;
+ }
+
+ @Override
+ public void setCamelContext(CamelContext camelContext) {
+ this.camelContext = camelContext;
+ }
+
+ /**
+ * Registers this {@link MDCService} on the {@link CamelContext} if not already registered.
+ */
+ public void init(CamelContext camelContext) {
+ if (!camelContext.hasService(this)) {
+ try {
+ // start this service eager so we init before Camel is starting up
+ camelContext.addService(this, true, true);
+ } catch (Exception e) {
+ throw RuntimeCamelException.wrapRuntimeCamelException(e);
+ }
+ }
+ }
+
+ @Override
+ public void doInit() {
+ ObjectHelper.notNull(camelContext, "CamelContext", this);
+ camelContext.getCamelContextExtension().addLogListener(new TracingLogListener());
+ }
+
+ private final class TracingLogListener implements LogListener {
+
+ @Override
+ public String onLog(Exchange exchange, CamelLogger camelLogger, String message) {
+ try {
+ // MDC setting here
+ MDC.put("exchangeID", exchange.getExchangeId());
+ } catch (Exception t) {
+ // This exception is ignored
+ LOG.warn("MDC: failed to store MDC data. This exception is ignored.", t);
+ }
+ return message;
+ }
+
+ @Override
+ public void afterLog(Exchange exchange, CamelLogger camelLogger, String message) {
+ MDC.clear();
+ }
+ }
+
+}
diff --git a/components/camel-mdc/src/test/resources/log4j2.properties b/components/camel-mdc/src/test/resources/log4j2.properties
new file mode 100644
index 00000000000..c9d7df800c7
--- /dev/null
+++ b/components/camel-mdc/src/test/resources/log4j2.properties
@@ -0,0 +1,30 @@
+## ---------------------------------------------------------------------------
+## 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.
+## ---------------------------------------------------------------------------
+appender.console.type = Console
+appender.console.name = console
+appender.console.layout.type = PatternLayout
+appender.console.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
+
+appender.file.type = File
+appender.file.name = file
+appender.file.fileName = target/camel-telemetry-test.log
+appender.file.append = true
+appender.file.layout.type = PatternLayout
+appender.file.layout.pattern = %d [%-15.15t] %-5p %-30.30c{1} - %m%n
+
+rootLogger.level = INFO
+rootLogger.appenderRef.file.ref = file
diff --git a/components/pom.xml b/components/pom.xml
index 1b87350f836..b4b07ebb810 100644
--- a/components/pom.xml
+++ b/components/pom.xml
@@ -215,6 +215,7 @@
<module>camel-mail</module>
<module>camel-mail-microsoft-oauth</module>
<module>camel-mapstruct</module>
+ <module>camel-mdc</module>
<module>camel-metrics</module>
<module>camel-micrometer</module>
<module>camel-micrometer-observability</module>
diff --git a/core/camel-api/src/main/java/org/apache/camel/spi/CamelMDCService.java b/core/camel-api/src/main/java/org/apache/camel/spi/CamelMDCService.java
new file mode 100644
index 00000000000..25252052788
--- /dev/null
+++ b/core/camel-api/src/main/java/org/apache/camel/spi/CamelMDCService.java
@@ -0,0 +1,27 @@
+/*
+ * 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.spi;
+
+import org.apache.camel.CamelContextAware;
+import org.apache.camel.Service;
+
+/**
+ * A Camel MDC service is a factory for Mapped Diagnostic Context service.
+ */
+public interface CamelMDCService extends Service, CamelContextAware {
+
+}
diff --git a/core/camel-api/src/main/java/org/apache/camel/spi/LogListener.java b/core/camel-api/src/main/java/org/apache/camel/spi/LogListener.java
index 04a741265fa..ab726f2cbb2 100644
--- a/core/camel-api/src/main/java/org/apache/camel/spi/LogListener.java
+++ b/core/camel-api/src/main/java/org/apache/camel/spi/LogListener.java
@@ -38,4 +38,16 @@ public interface LogListener {
*/
String onLog(Exchange exchange, CamelLogger camelLogger, String message);
+ /**
+ * Invoked right after Log component or Log EIP logs. The method can be used for cleaning up any transient
+ * information used during onLog execution.
+ *
+ * @param exchange camel exchange
+ * @param camelLogger {@link CamelLogger}
+ * @param message log message
+ */
+ default void afterLog(Exchange exchange, CamelLogger camelLogger, String message) {
+ // NO-OP
+ }
+
}
diff --git a/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java b/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java
index 0491209964e..5babd94ca6a 100644
--- a/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java
+++ b/core/camel-core-processor/src/main/java/org/apache/camel/processor/LogProcessor.java
@@ -78,6 +78,9 @@ public class LogProcessor extends BaseProcessorSupport implements Traceable, IdA
msg = fireListeners(exchange, msg);
}
logger.doLog(msg);
+ if (listeners != null && !listeners.isEmpty()) {
+ closeListeners(exchange, msg);
+ }
} catch (Exception e) {
exchange.setException(e);
}
@@ -105,6 +108,23 @@ public class LogProcessor extends BaseProcessorSupport implements Traceable, IdA
return message;
}
+ private void closeListeners(Exchange exchange, String message) {
+ for (LogListener listener : listeners) {
+ if (listener == null) {
+ continue;
+ }
+ try {
+ listener.afterLog(exchange, logger, message);
+ } catch (Exception t) {
+ LOG.warn("Ignoring an exception: {} thrown by: {} caused by: {}", t.getClass().getName(),
+ listener.getClass().getName(), t.getMessage());
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("", t);
+ }
+ }
+ }
+ }
+
@Override
public String toString() {
return id;
diff --git a/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java b/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java
new file mode 100644
index 00000000000..9707c284526
--- /dev/null
+++ b/core/camel-main/src/generated/java/org/apache/camel/main/MdcConfigurationPropertiesConfigurer.java
@@ -0,0 +1,48 @@
+/* Generated by camel build tools - do NOT edit this file! */
+package org.apache.camel.main;
+
+import javax.annotation.processing.Generated;
+import java.util.Map;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
+import org.apache.camel.spi.PropertyConfigurerGetter;
+import org.apache.camel.spi.ConfigurerStrategy;
+import org.apache.camel.spi.GeneratedPropertyConfigurer;
+import org.apache.camel.util.CaseInsensitiveMap;
+import org.apache.camel.main.MdcConfigurationProperties;
+
+/**
+ * Generated by camel build tools - do NOT edit this file!
+ */
+@Generated("org.apache.camel.maven.packaging.GenerateConfigurerMojo")
+@SuppressWarnings("unchecked")
+public class MdcConfigurationPropertiesConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter {
+
+ private static final Map<String, Object> ALL_OPTIONS;
+ static {
+ Map<String, Object> map = new CaseInsensitiveMap();
+ ALL_OPTIONS = map;
+ }
+
+ @Override
+ public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
+ return false;
+ }
+
+ @Override
+ public Map<String, Object> getAllOptions(Object target) {
+ return ALL_OPTIONS;
+ }
+
+ @Override
+ public Class<?> getOptionType(String name, boolean ignoreCase) {
+ return null;
+ }
+
+ @Override
+ public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
+ return null;
+ }
+}
+
diff --git a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
index bb1e632f40c..6dbbe63d36a 100644
--- a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
+++ b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
@@ -21,6 +21,7 @@
{ "name": "camel.opentelemetry", "description": "Camel OpenTelemetry configurations", "sourceType": "org.apache.camel.main.OtelConfigurationProperties" },
{ "name": "camel.opentelemetry2", "description": "Camel OpenTelemetry 2 configurations", "sourceType": "org.apache.camel.main.Otel2ConfigurationProperties" },
{ "name": "camel.telemetryDev", "description": "Camel Telemetry Dev configurations", "sourceType": "org.apache.camel.main.TelemetryDevConfigurationProperties" },
+ { "name": "camel.mdc", "description": "Camel MDC configurations", "sourceType": "org.apache.camel.main.MdcConfigurationProperties" },
{ "name": "camel.metrics", "description": "Camel Micrometer Metrics configurations", "sourceType": "org.apache.camel.main.MetricsConfigurationProperties" },
{ "name": "camel.faulttolerance", "description": "Fault Tolerance EIP Circuit Breaker configurations", "sourceType": "org.apache.camel.main.FaultToleranceConfigurationProperties" },
{ "name": "camel.resilience4j", "description": "Resilience4j EIP Circuit Breaker configurations", "sourceType": "org.apache.camel.main.Resilience4jConfigurationProperties" },
diff --git a/core/camel-main/src/generated/resources/META-INF/services/org/apache/camel/configurer/org.apache.camel.main.MdcConfigurationProperties b/core/camel-main/src/generated/resources/META-INF/services/org/apache/camel/configurer/org.apache.camel.main.MdcConfigurationProperties
new file mode 100644
index 00000000000..a95186bdc04
--- /dev/null
+++ b/core/camel-main/src/generated/resources/META-INF/services/org/apache/camel/configurer/org.apache.camel.main.MdcConfigurationProperties
@@ -0,0 +1,2 @@
+# Generated by camel build tools - do NOT edit this file!
+class=org.apache.camel.main.MdcConfigurationPropertiesConfigurer
diff --git a/core/camel-main/src/main/docs/main.adoc b/core/camel-main/src/main/docs/main.adoc
index 8dac7ccd593..78a79e8b33a 100644
--- a/core/camel-main/src/main/docs/main.adoc
+++ b/core/camel-main/src/main/docs/main.adoc
@@ -562,6 +562,15 @@ The camel.telemetryDev supports 4 options, which are listed below.
|===
+=== Camel MDC configurations
+The camel.mdc supports 0 options, which are listed below.
+
+[width="100%",cols="2,5,^1,2",options="header"]
+|===
+| Name | Description | Default | Type
+|===
+
+
=== Camel Micrometer Metrics configurations
The camel.metrics supports 14 options, which are listed below.
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
index 2662a60413b..84e69be5b48 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
@@ -67,6 +67,7 @@ import org.apache.camel.spi.AutowiredLifecycleStrategy;
import org.apache.camel.spi.BacklogTracer;
import org.apache.camel.spi.CamelBeanPostProcessor;
import org.apache.camel.spi.CamelEvent;
+import org.apache.camel.spi.CamelMDCService;
import org.apache.camel.spi.CamelMetricsService;
import org.apache.camel.spi.CamelTracingService;
import org.apache.camel.spi.CompileStrategy;
@@ -136,7 +137,7 @@ public abstract class BaseMainSupport extends BaseService {
"camel.context.", "camel.resilience4j.", "camel.faulttolerance.",
"camel.rest.", "camel.vault.", "camel.threadpool.", "camel.health.",
"camel.lra.", "camel.opentelemetry2.", "camel.opentelemetry.",
- "camel.telemetryDev.", "camel.management.", "camel.metrics.", "camel.routeTemplate",
+ "camel.telemetryDev.", "camel.management.", "camel.mdc.", "camel.metrics.", "camel.routeTemplate",
"camel.devConsole.", "camel.variable.", "camel.beans.", "camel.globalOptions.",
"camel.server.", "camel.ssl.", "camel.debug.", "camel.trace.", "camel.routeController." };
@@ -1283,6 +1284,7 @@ public abstract class BaseMainSupport extends BaseService {
OrderedLocationProperties lraProperties = new OrderedLocationProperties();
OrderedLocationProperties otelProperties = new OrderedLocationProperties();
OrderedLocationProperties otel2Properties = new OrderedLocationProperties();
+ OrderedLocationProperties mdcProperties = new OrderedLocationProperties();
OrderedLocationProperties telemetryDevProperties = new OrderedLocationProperties();
OrderedLocationProperties metricsProperties = new OrderedLocationProperties();
OrderedLocationProperties routeTemplateProperties = new OrderedLocationProperties();
@@ -1359,6 +1361,12 @@ public abstract class BaseMainSupport extends BaseService {
String option = key.substring(19);
validateOptionAndValue(key, option, value);
telemetryDevProperties.put(loc, optionKey(option), value);
+ } else if (startsWithIgnoreCase(key, "camel.mdc.")) {
+ // grab the value
+ String value = prop.getProperty(key);
+ String option = key.substring(10);
+ validateOptionAndValue(key, option, value);
+ mdcProperties.put(loc, optionKey(option), value);
} else if (startsWithIgnoreCase(key, "camel.metrics.")) {
// grab the value
String value = prop.getProperty(key);
@@ -1525,6 +1533,11 @@ public abstract class BaseMainSupport extends BaseService {
setMetricsProperties(camelContext, metricsProperties, mainConfigurationProperties.isAutoConfigurationFailFast(),
autoConfiguredProperties);
}
+ if (!mdcProperties.isEmpty() || mainConfigurationProperties.hasMdcConfiguration()) {
+ LOG.debug("Auto-configuring MDC from loaded properties: {}", mdcProperties.size());
+ setMdcProperties(camelContext, mdcProperties, mainConfigurationProperties.isAutoConfigurationFailFast(),
+ autoConfiguredProperties);
+ }
if (!devConsoleProperties.isEmpty()) {
LOG.debug("Auto-configuring Dev Console from loaded properties: {}", devConsoleProperties.size());
setDevConsoleProperties(camelContext, devConsoleProperties,
@@ -1656,6 +1669,11 @@ public abstract class BaseMainSupport extends BaseService {
LOG.warn("Property not auto-configured: camel.management.{}={}", k, v);
});
}
+ if (!mdcProperties.isEmpty()) {
+ mdcProperties.forEach((k, v) -> {
+ LOG.warn("Property not auto-configured: camel.mdc.{}={}", k, v);
+ });
+ }
// and call after all properties are set
DefaultConfigurationConfigurer.afterPropertiesSet(camelContext);
@@ -1851,6 +1869,28 @@ public abstract class BaseMainSupport extends BaseService {
}
}
+ private void setMdcProperties(
+ CamelContext camelContext, OrderedLocationProperties mdcProperties,
+ boolean failIfNotSet, OrderedLocationProperties autoConfiguredProperties)
+ throws Exception {
+
+ String loc = mdcProperties.getLocation("enabled");
+ Object obj = mdcProperties.remove("enabled");
+ if (ObjectHelper.isNotEmpty(obj)) {
+ autoConfiguredProperties.put(loc, "camel.mdc.enabled", obj.toString());
+ }
+ boolean enabled = obj != null ? CamelContextHelper.parseBoolean(camelContext, obj.toString()) : true;
+ if (enabled) {
+ CamelMDCService mdc = resolveMDCService(camelContext);
+ setPropertiesOnTarget(camelContext, mdc, mdcProperties, "camel.mdc.", failIfNotSet, true,
+ autoConfiguredProperties);
+ if (camelContext.hasService(CamelMDCService.class) == null) {
+ // add as service so tracing can be active
+ camelContext.addService(mdc, true, true);
+ }
+ }
+ }
+
private void setTelemetryDevProperties(
CamelContext camelContext, OrderedLocationProperties telemetryDevProperties,
boolean failIfNotSet, OrderedLocationProperties autoConfiguredProperties)
@@ -2741,6 +2781,20 @@ public abstract class BaseMainSupport extends BaseService {
return answer;
}
+ private static CamelMDCService resolveMDCService(CamelContext camelContext) throws Exception {
+ CamelMDCService answer = camelContext.hasService(CamelMDCService.class);
+ if (answer == null) {
+ answer = camelContext.getRegistry().findSingleByType(CamelMDCService.class);
+ }
+ if (answer == null) {
+ answer = camelContext.getCamelContextExtension().getBootstrapFactoryFinder()
+ .newInstance("mdc-service", CamelMDCService.class)
+ .orElseThrow(() -> new IllegalArgumentException(
+ "Cannot find OpenTelemetryTracer2 on classpath. Add camel-opentelemetry2 to classpath."));
+ }
+ return answer;
+ }
+
private static MainHttpServerFactory resolveMainHttpServerFactory(CamelContext camelContext) {
// lookup in service registry first
MainHttpServerFactory answer = camelContext.getRegistry().findSingleByType(MainHttpServerFactory.class);
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java b/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
index 1048cd15014..c95aab73387 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
@@ -61,6 +61,7 @@ public class MainConfigurationProperties extends DefaultConfigurationProperties<
private LraConfigurationProperties lraConfigurationProperties;
private OtelConfigurationProperties otelConfigurationProperties;
private Otel2ConfigurationProperties otel2ConfigurationProperties;
+ private MdcConfigurationProperties mdcConfigurationProperties;
private TelemetryDevConfigurationProperties telemetryDevConfigurationProperties;
private MetricsConfigurationProperties metricsConfigurationProperties;
private ThreadPoolConfigurationProperties threadPoolProperties;
@@ -97,6 +98,10 @@ public class MainConfigurationProperties extends DefaultConfigurationProperties<
telemetryDevConfigurationProperties.close();
telemetryDevConfigurationProperties = null;
}
+ if (mdcConfigurationProperties != null) {
+ mdcConfigurationProperties.close();
+ mdcConfigurationProperties = null;
+ }
if (metricsConfigurationProperties != null) {
metricsConfigurationProperties.close();
metricsConfigurationProperties = null;
@@ -237,6 +242,13 @@ public class MainConfigurationProperties extends DefaultConfigurationProperties<
return telemetryDevConfigurationProperties != null;
}
+ /**
+ * Whether there has been any MDC configuration specified
+ */
+ public boolean hasMdcConfiguration() {
+ return mdcConfigurationProperties != null;
+ }
+
/**
* To configure Micrometer metrics.
*/
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java b/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java
new file mode 100644
index 00000000000..4d678032669
--- /dev/null
+++ b/core/camel-main/src/main/java/org/apache/camel/main/MdcConfigurationProperties.java
@@ -0,0 +1,57 @@
+/*
+ * 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.main;
+
+import org.apache.camel.spi.BootstrapCloseable;
+import org.apache.camel.spi.Configurer;
+
+/**
+ * Global configuration for MDC
+ */
+@Configurer(extended = true)
+public class MdcConfigurationProperties implements BootstrapCloseable {
+
+ private MainConfigurationProperties parent;
+
+ private boolean enabled;
+
+ public MdcConfigurationProperties(MainConfigurationProperties parent) {
+ this.parent = parent;
+ }
+
+ public MainConfigurationProperties end() {
+ return parent;
+ }
+
+ @Override
+ public void close() {
+ parent = null;
+ }
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ /**
+ * To enable Mdc
+ */
+ public MdcConfigurationProperties withEnabled(boolean enabled) {
+ this.enabled = enabled;
+ return this;
+ }
+
+}
diff --git a/core/camel-support/src/main/java/org/apache/camel/support/processor/CamelLogProcessor.java b/core/camel-support/src/main/java/org/apache/camel/support/processor/CamelLogProcessor.java
index d6c9ec0192d..6162ab3247b 100644
--- a/core/camel-support/src/main/java/org/apache/camel/support/processor/CamelLogProcessor.java
+++ b/core/camel-support/src/main/java/org/apache/camel/support/processor/CamelLogProcessor.java
@@ -102,6 +102,7 @@ public class CamelLogProcessor extends AsyncProcessorSupport implements IdAware,
}
output = fireListeners(exchange, output);
logger.log(output);
+ closeListeners(exchange, output);
}
callback.done(true);
return true;
@@ -115,6 +116,7 @@ public class CamelLogProcessor extends AsyncProcessorSupport implements IdAware,
}
output = fireListeners(exchange, output);
logger.log(output, exception);
+ closeListeners(exchange, output);
}
}
@@ -126,6 +128,7 @@ public class CamelLogProcessor extends AsyncProcessorSupport implements IdAware,
}
output = fireListeners(exchange, output);
logger.log(output);
+ closeListeners(exchange, output);
}
}
@@ -150,6 +153,25 @@ public class CamelLogProcessor extends AsyncProcessorSupport implements IdAware,
return message;
}
+ private void closeListeners(Exchange exchange, String message) {
+ if (listeners == null || listeners.isEmpty()) {
+ return;
+ }
+ for (LogListener listener : listeners) {
+ if (listener == null) {
+ continue;
+ }
+ try {
+ listener.afterLog(exchange, logger, message);
+ } catch (Exception t) {
+ LOG.warn("Ignoring an exception thrown by {}: {}", listener.getClass().getName(), t.getMessage());
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("", t);
+ }
+ }
+ }
+ }
+
public CamelLogger getLogger() {
return logger;
}
diff --git a/docs/components/modules/others/examples/json/mdc.json b/docs/components/modules/others/examples/json/mdc.json
new file mode 120000
index 00000000000..0d57f5bed57
--- /dev/null
+++ b/docs/components/modules/others/examples/json/mdc.json
@@ -0,0 +1 @@
+../../../../../../components/camel-mdc/src/generated/resources/mdc.json
\ No newline at end of file
diff --git a/docs/components/modules/others/nav.adoc b/docs/components/modules/others/nav.adoc
index 02b181394d9..16495e4d3ac 100644
--- a/docs/components/modules/others/nav.adoc
+++ b/docs/components/modules/others/nav.adoc
@@ -28,6 +28,7 @@
** xref:lra.adoc[LRA]
** xref:mail-microsoft-oauth.adoc[Mail Microsoft Oauth]
** xref:main.adoc[Main]
+** xref:mdc.adoc[Mdc]
** xref:observation.adoc[Micrometer Observability]
** xref:micrometer-observability.adoc[Micrometer Observability 2]
** xref:micrometer-prometheus.adoc[Micrometer Prometheus]
diff --git a/docs/components/modules/others/pages/mdc.adoc b/docs/components/modules/others/pages/mdc.adoc
new file mode 120000
index 00000000000..eec3ea2ffd3
--- /dev/null
+++ b/docs/components/modules/others/pages/mdc.adoc
@@ -0,0 +1 @@
+../../../../../components/camel-mdc/src/main/docs/mdc.adoc
\ No newline at end of file
diff --git a/parent/pom.xml b/parent/pom.xml
index 2442a93df2a..2a14a54308d 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -1937,6 +1937,11 @@
<artifactId>camel-master</artifactId>
<version>${project.version}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.camel</groupId>
+ <artifactId>camel-mdc</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-metrics</artifactId>
diff --git a/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java b/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java
index e919a83c765..324dd3d4176 100644
--- a/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java
+++ b/tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PrepareCamelMainMojo.java
@@ -443,6 +443,9 @@ public class PrepareCamelMainMojo extends AbstractGeneratorMojo {
model.getGroups().add(new MainGroupModel(
"camel.telemetryDev", "Camel Telemetry Dev configurations",
"org.apache.camel.main.TelemetryDevConfigurationProperties"));
+ model.getGroups().add(new MainGroupModel(
+ "camel.mdc", "Camel MDC configurations",
+ "org.apache.camel.main.MdcConfigurationProperties"));
model.getGroups().add(new MainGroupModel(
"camel.metrics", "Camel Micrometer Metrics configurations",
"org.apache.camel.main.MetricsConfigurationProperties"));