日志通道适配器

<logging-channel-adapter> 通常与线线程探测器(wire tap)结合使用,正如 线线程探测器 中讨论的那样。但是,它也可以用作任何流程的最终消费者。例如,考虑一个流程以返回结果的 <service-activator> 结束,但您希望丢弃该结果。为此,您可以将结果发送到 NullChannel。或者,您可以将其路由到一个 INFO 级别的 <logging-channel-adapter>。这样,当日志级别为 INFO 时,您可以看到被丢弃的消息,但在日志级别为 WARN (例如) 时则看不到。使用 NullChannel,您只有在日志级别为 DEBUG 时才能看到被丢弃的消息。以下列表显示了 logging-channel-adapter 元素的所有可能属性

<int:logging-channel-adapter
    channel="" (1)
    level="INFO" (2)
    expression="" (3)
    log-full-message="false" (4)
    logger-name="" /> (5)
1 将日志适配器连接到上游组件的通道。
2 发送到此适配器的消息将被记录的日志级别。默认值:INFO
3 表示消息中哪些部分将被精确记录的 SpEL 表达式。默认值:payload — 仅记录载荷。如果指定了 log-full-message,则不能指定此属性。
4 当为 true 时,记录整条消息(包括消息头)。默认值:false — 仅记录载荷。如果指定了 expression,则不能指定此属性。
5 指定日志记录器(在 log4j 中称为 category)的 name。用于标识此适配器创建的日志消息。这使得可以为单个适配器设置日志名称(在日志子系统中)。默认情况下,所有适配器都在以下名称下记录日志:org.springframework.integration.handler.LoggingHandler

使用 Java 配置

以下 Spring Boot 应用展示了使用 Java 配置 LoggingHandler 的示例

@SpringBootApplication
public class LoggingJavaApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =
             new SpringApplicationBuilder(LoggingJavaApplication.class)
                    .web(false)
                    .run(args);
         MyGateway gateway = context.getBean(MyGateway.class);
         gateway.sendToLogger("foo");
    }

    @Bean
    @ServiceActivator(inputChannel = "logChannel")
    public LoggingHandler logging() {
        LoggingHandler adapter = new LoggingHandler(LoggingHandler.Level.DEBUG);
        adapter.setLoggerName("TEST_LOGGER");
        adapter.setLogExpressionString("headers.id + ': ' + payload");
        return adapter;
    }

    @MessagingGateway(defaultRequestChannel = "logChannel")
    public interface MyGateway {

        void sendToLogger(String data);

    }

}

使用 Java DSL 配置

以下 Spring Boot 应用展示了使用 Java DSL 配置日志通道适配器的示例

@SpringBootApplication
public class LoggingJavaApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context =
             new SpringApplicationBuilder(LoggingJavaApplication.class)
                    .web(false)
                    .run(args);
         MyGateway gateway = context.getBean(MyGateway.class);
         gateway.sendToLogger("foo");
    }

    @Bean
    public IntegrationFlow loggingFlow() {
        return IntegrationFlow.from(MyGateway.class)
                     .log(LoggingHandler.Level.DEBUG, "TEST_LOGGER",
                           m -> m.getHeaders().getId() + ": " + m.getPayload());
    }

    @MessagingGateway
    public interface MyGateway {

        void sendToLogger(String data);

    }

}