问题描述

在使用Azure Event Hub的SDK时候,常规情况下,发现示例代码中并没有SDK内部的日志输出。因为在Java项目中,没有添加 SLF4J 依赖,已致于在启动时候有如下提示:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

那么,有什么方便的办法,能把SDK中,内部处理Event Hub的日志打印出来,并且保存在日志文件中呢?

问题解答

是的,如提示所说,使用 SLF4J 就可以了。因为Azure Event Hub SDK中使用 (com.azure.core.util.logging.ClientLogger) 对日志进行输出,所以在最外层(应用代码级)就需要有一个接收日志的Provider,那就是SLF4J。

下面的步骤,就是展示如何添加SLF4J依赖,如何添加输出到文件,输出到Console的配置,最后查看输出结果。

前提要求:根据官方示例代码,已经成功运行消费端应用:https://docs.azure.cn/zh-cn/event-hubs/event-hubs-java-get-started-send (文末附带本文的示例代码)

第一步:在 pom.xml 中添加 SLF4J 的3个依赖项

    <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

第二步:在 .\src\main\resources 目录中添加 log4j.properties 文件,并设置最关键的 日志输出级别路径格式

# Root logger option
log4j.rootLogger=INFO, stdout, FILE
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n # Direct log messages to file # Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=Logs/log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

第三步: 检查输出结果

1)实验项目的文件结构

2)pom.xml 中添加的 slf4j 依赖

3)为日志输出到文件和控制台配置属性

4)查看文件日志输出

5)查看控制台日志输出

附录一:本文实验中的全部代码

1:POM.XML 文件内容

<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>com.example</groupId>
<artifactId>ConsumeMessageAbort</artifactId>
<version>1.0-SNAPSHOT</version> <name>ConsumeMessageAbort</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs</artifactId>
<version>5.12.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-messaging-eventhubs-checkpointstore-blob</artifactId>
<version>1.14.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<archive>
<manifest>
<mainClass>com.example.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>

2:src\main\resources\log4j.properties 文件内容

# Root logger option
log4j.rootLogger=INFO, stdout, FILE
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n # Direct log messages to file
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=Logs/log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

3:src\main\java\com\example\App.java 文件内容

package com.example;

import com.azure.messaging.eventhubs.EventData;
import com.azure.messaging.eventhubs.EventHubClientBuilder;
import com.azure.messaging.eventhubs.EventHubConsumerAsyncClient;
import com.azure.messaging.eventhubs.EventProcessorClientBuilder; import java.io.IOException;
import java.sql.Date;
import java.time.Instant;
import java.time.temporal.TemporalUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Hello world!
*
*/
public class App { final static Logger logger = LoggerFactory.getLogger(App.class);
private static final String azureEventHubConnectionString = "event hub namespace connection string";
private static final String azureEventHubHostName = "event hub name"; public static void main(String[] args) throws IOException {
System.out.println("Hello World!"); EventHubConsumerAsyncClient consumer = new EventHubClientBuilder()
.connectionString(azureEventHubConnectionString, azureEventHubHostName)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildAsyncConsumerClient(); try {
consumer.receive(true).subscribe(
event -> {
EventData data = event.getData();
String message = "SequenceNumber is" + data.getSequenceNumber().toString()
+ " The eventData is "
+ data.getBodyAsString();
System.out.println(message);
logger.info(message);
},
error -> logger.error("The iot hub failed to listen for messages, error is {}" + error.toString())); } catch (Exception e) {
consumer = new EventHubClientBuilder()
.connectionString(azureEventHubConnectionString, azureEventHubHostName)
.consumerGroup(EventHubClientBuilder.DEFAULT_CONSUMER_GROUP_NAME)
.buildAsyncConsumerClient();
System.out.println("recollect consumer");
logger.warn("recollect consumer");
} System.out.println("Press enter to stop.");
logger.info("Press enter to stop.");
System.in.read(); System.out.println("...End...");
} }

4:文件结构

参考资料

开启 Apache Flink 制造者 Producer 示例代码中的日志输出 : https://www.cnblogs.com/lulight/p/15789878.html

使用 Java 向/从 Azure 事件中心 (azure-messaging-eventhubs) 发送/接收事件 : https://docs.azure.cn/zh-cn/event-hubs/event-hubs-java-get-started-send

【Azure 事件中心】 org.slf4j.Logger 收集 Event Hub SDK(Java) 输出日志并以文件形式保存的更多相关文章

  1. 【Azure 事件中心】在微软云中国区 (Mooncake) 上实验以Apache Kafka协议方式发送/接受Event Hubs消息 (Java版)

    问题描述 事件中心提供 Kafka 终结点,现有的基于 Kafka 的应用程序可将该终结点用作运行你自己的 Kafka 群集的替代方案. 事件中心可与许多现有 Kafka 应用程序配合使用.在Azur ...

  2. 【Azure 事件中心】Azure Event Hub 新功能尝试 -- 异地灾难恢复 (Geo-Disaster Recovery)

    问题描述 关于Event Hub(事件中心)的灾备方案,大多数就是新建另外一个备用的Event Hub,当主Event Hub出现不可用的情况时,就需要切换到备Event Hub上. 而在切换的过程中 ...

  3. 【Azure 事件中心】使用Azure AD认证方式创建Event Hub Consume Client + 自定义Event Position

    问题描述 当使用SDK连接到Azure Event Hub时,最常规的方式为使用连接字符串.这种做法参考官网文档就可成功完成代码:https://docs.azure.cn/zh-cn/event-h ...

  4. 【Azure 事件中心】Event Hub 无法连接,出现 Did not observe any item or terminal signal within 60000ms in 'flatMapMany' 的错误消息

    问题描述 使用Java SDK连接Azure Event Hub,一直出现 java.util.concurrent.TimeoutException 异常, 消息为:java.util.concur ...

  5. 【Azure 事件中心】EPH (EventProcessorHost) 消费端观察到多次Shutdown,LeaseLost的error信息,这是什么情况呢?

    问题详情 使用EPH获取Event Hub数据时,多次出现连接shutdown和LeaseLost的error  ,截取某一次的error log如: Time:2021-03-10 08:43:48 ...

  6. 【Azure 事件中心】为应用程序网关(Application Gateway with WAF) 配置诊断日志,发送到事件中心

    问题描述 在Application Gateway中,开启WAF(Web application firewall)后,现在需要把访问的日志输出到第三方分析代码中进行分析,如何来获取WAF的诊断日志呢 ...

  7. 【Azure 事件中心】azure-spring-cloud-stream-binder-eventhubs客户端组件问题, 实践消息非顺序可达

    问题描述 查阅了Azure的官方文档( 将事件发送到特定分区: https://docs.azure.cn/zh-cn/event-hubs/event-hubs-availability-and-c ...

  8. 【Azure 事件中心】在Service Bus Explorer工具种查看到EventHub数据在分区中的各种属性问题

    问题描述 通过Service Bus Explorer工具,查看到Event Hub的属性值,从而产生的问题及讨论: Size in Bytes:   这个是表示当前分区可以存储的最大字节数吗? La ...

  9. 【事件中心 Azure Event Hub】关于EventHub中出现Error时候的一些问题(偶发错误,EventHub后台升级,用户端错误,Retry机制的重要性)

    请问对偶发的定义是多少频率? 针对偶发的定义,主要是看发生的时间非常短,次数极少(如 10次以内),并且发生的时候EventHub其他分区或其他连接都是正常接收和发送数据.所以对于频率是没有明确的定义 ...

随机推荐

  1. 记一次python + selenium小项目出现的问题与解决办法

    记一次python + selenium小项目出现的问题与解决办法 如何接入代理 def crawl_xdaili(self):#代理 可不用 需要时 解除注释 """ ...

  2. KingbaseFlySync 专用机版本升级

    关键字: KingbaseFlySync.Linux.x86_64.mips64el.aarch64.Java 专线机版本升级 1.备份kfs配置文件和rename问题,kufl目录 fsrepctl ...

  3. kubernetes 调度器

    调度器 kube-scheduler 是 kubernetes 的核心组件之一,主要负责整个集群资源的调度功能,根据特定的调度算法和策略,将 Pod 调度到最优的工作节点上面去,从而更加合理.更加充分 ...

  4. Dockerfile文件全面详解

    Docker 可以通过读取 Dockerfile 中的指令自动构建镜像.Dockerfile 是一个文本文档,其中包含了用户创建镜像的所有命令和说明. 一. 变量 变量用 $variable_name ...

  5. alertmanager配置文件详解

    global: smtp_smarthost: 'localhost:25' smtp_from: 'alertmanager@example.org' #用于邮件通知的P发件人 route: #每个 ...

  6. Node Exporter监控指标

    访问http://localhost:9100/metrics,可以看到当前node exporter获取到的当前主机的所有监控数据,如下所示: 每一个监控指标之前都会有一段类似于如下形式的信息: # ...

  7. 8. 使用Fluentd+MongoDB采集Apache日志

    Fluentd+MongoDB,用以实时收集半结构化数据. 背景知识 日志接入Fluentd后,会以json的格式在Fluentd内部进行路由.这就决定了Fluentd处理日志的方式是非常灵活的,它将 ...

  8. 关于使用git传输文件到GitHub

    git status(查看本地git仓库情况) git add "文件名(精确到文件拓展名)" git commit -m "说明"(提交到上传缓存区域) gi ...

  9. acwing1782 Dynamic Rankings (整体二分)

    和整体二分的模板相比,多了修改操作. 1 #include<bits/stdc++.h> 2 using namespace std; 3 const int N=1e5+10,INF=1 ...

  10. IPv4 与 IPv6的区别

    在介绍 IPv4 到 IPv6 区别之前,我们先来简单了解一下 IPv4 和 IPv6. IPv4 网际协议版本4(英语:Internet Protocol version 4,IPv4),又称互联网 ...