使用向控制台输出 SDK 指标 AWS SDK for Java 2.x - AWS SDK for Java 2.x

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用向控制台输出 SDK 指标 AWS SDK for Java 2.x

LoggingMetricPublisher实现将指标直接输出到应用程序的控制台或日志文件。这种方法非常适合开发、调试和了解 SDK 收集的指标,而无需像 Amazon 这样的外部服务 CloudWatch。

CloudWatchMetricPublisher和不同EmfMetricLoggingPublisherLoggingMetricPublisher它提供即时输出,没有延迟或外部依赖。这使其非常适合本地开发和故障排除场景。

何时使用 LoggingMetricPublisher

在需要执行以下操作时使用 LoggingMetricPublisher

  • 在开发过程中调试指标收集

  • 了解 SDK 为您的运营收集了哪些指标

  • 对本地性能问题进行故障排除

  • 不依赖外部服务的测试指标收集

  • 立即在控制台或日志文件中查看指标

注意

LoggingMetricPublisher不建议在需要持久指标存储和分析功能的生产环境中使用。

为指标设置控制台日志

要查看LoggingMetricPublisher输出,请将您的日志框架配置为显示INFO级别消息。以下log4j2.xml配置可确保指标显示在您的控制台中:

<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="ConsoleAppender" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </Appenders> <Loggers> <Root level="INFO"> <AppenderRef ref="ConsoleAppender"/> </Root> <!-- Ensure LoggingMetricPublisher output appears. --> <Logger name="software.amazon.awssdk.metrics.LoggingMetricPublisher" level="INFO" /> </Loggers> </Configuration>

此配置指示 SDK 在INFO级别将指标输出到您的控制台。LoggingMetricPublisher记录器配置可确保即使您的根记录器使用更高的级别(如或),也能显示指标输出。WARN ERROR

为服务客户端启用控制台指标

以下示例说明如何创建并将其与 Amazon 简单存储服务客户端一起使用:LoggingMetricPublisher

import software.amazon.awssdk.metrics.LoggingMetricPublisher; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; // Create a LoggingMetricPublisher with default settings. MetricPublisher metricPublisher = LoggingMetricPublisher.create(); // Add the publisher to your service client. S3Client s3Client = S3Client.builder() .region(Region.US_EAST_1) .overrideConfiguration(config -> config.addMetricPublisher(metricPublisher)) .build(); // Make requests - metrics will appear in your console. s3Client.listBuckets(); // Clean up resources. metricPublisher.close(); s3Client.close();

选择指标输出格式

LoggingMetricPublisher支持两种输出格式:

  • PL@@ AIN 格式(默认):将指标输出为紧凑的单行条目

  • PRETTY 格式:以多行、人类可读的格式输出指标

以下示例说明了如何在开发过程中使用 PRETTY 格式以便于阅读:

import org.slf4j.event.Level; import software.amazon.awssdk.metrics.LoggingMetricPublisher; // Create a LoggingMetricPublisher with PRETTY format. MetricPublisher prettyMetricPublisher = LoggingMetricPublisher.create( Level.INFO, LoggingMetricPublisher.Format.PRETTY ); // Use with your service client. S3Client s3Client = S3Client.builder() .region(Region.US_EAST_1) .overrideConfiguration(config -> config.addMetricPublisher(prettyMetricPublisher)) .build();

完整示例

以下示例演示LoggingMetricPublisher了两种使用方式:

  • 在服务客户层面

  • 对于单个请求

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import software.amazon.awssdk.metrics.LoggingMetricPublisher; import software.amazon.awssdk.metrics.MetricPublisher; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.ListBucketsRequest; import software.amazon.awssdk.services.s3.model.ListBucketsResponse; /** * Demonstrates how to use LoggingMetricPublisher with AWS S3 SDK for Java 2.x. * <p> * This demo focuses on the S3 listBuckets operation to show how metrics are collected * and logged to the console for development and debugging purposes. * <p> * LoggingMetricPublisher is ideal for: * - Development and debugging * - Console output for troubleshooting * - Understanding what metrics are being collected * - Testing metric collection without external dependencies */ public class S3LoggingMetricPublisherDemo { private static final Logger logger = LoggerFactory.getLogger(S3LoggingMetricPublisherDemo.class); public static void main(String[] args) { S3LoggingMetricPublisherDemo demo = new S3LoggingMetricPublisherDemo(); demo.demonstrateUsage(); } /** * Demonstrates basic usage with S3Client and metrics enabled at the client level. */ private void demonstrateUsage() { // Create a LoggingMetricPublisher with default settings. The SDK logs metrics as text in a single line. // The default settings are equivalent to using `LoggingMetricPublisher.Format.PLAIN`. MetricPublisher metricPublisher = LoggingMetricPublisher.create(); // Create an S3 client with metrics enabled. try (S3Client s3Client = S3Client.builder() .region(Region.US_EAST_1) .overrideConfiguration(config -> config.addMetricPublisher(metricPublisher)) .build()) { // Make the listBuckets request - metrics will be logged to console. ListBucketsResponse response = s3Client.listBuckets(ListBucketsRequest.builder().build()); // The next block shows the using a different LoggingMetricPublisher with a `PRETTY` format. // Since the metric publisher is added to the request using the `overrideConfiguration`, this formatting // applies only to the one request. try { s3Client.listBuckets(ListBucketsRequest.builder() .overrideConfiguration(config -> config .addMetricPublisher(LoggingMetricPublisher.create( Level.INFO, LoggingMetricPublisher.Format.PRETTY))) .build()); } catch (Exception e) { logger.info("Request failed with metrics logged: {}", e.getMessage()); } logger.info("Found {} buckets in your AWS account.", response.buckets().size()); } catch (Exception e) { logger.error("Error during S3 operation: {}", e.getMessage()); logger.info("Note: This is expected if AWS credentials are not configured."); } // Close the metric publisher to flush any remaining metrics. metricPublisher.close(); } }

该代码将以下内容记录到控制台:

INFO LoggingMetricPublisher - Metrics published: MetricCollection(name=ApiCall, metrics=[MetricRecord(metric=MarshallingDuration, value=PT0.005409792S), MetricRecord(metric=RetryCount, value=0), MetricRecord(metric=ApiCallSuccessful, value=true), MetricRecord(metric=OperationName, value=ListBuckets), MetricRecord(metric=EndpointResolveDuration, value=PT0.000068S), MetricRecord(metric=ApiCallDuration, value=PT0.163802958S), MetricRecord(metric=CredentialsFetchDuration, value=PT0.145686542S), MetricRecord(metric=ServiceEndpoint, value=https://s3.amazonaws.com), MetricRecord(metric=ServiceId, value=S3)], children=[MetricCollection(name=ApiCallAttempt, metrics=[MetricRecord(metric=TimeToFirstByte, value=PT0.138816S), MetricRecord(metric=SigningDuration, value=PT0.007803459S), MetricRecord(metric=ReadThroughput, value=165153.96002660287), MetricRecord(metric=ServiceCallDuration, value=PT0.138816S), MetricRecord(metric=AwsExtendedRequestId, value=e13Swj3uwn0qP1Oz+m7II5OGq7jf8xxT8H18iDfRBCQmDg+gU4ek91Xrsl8XxRLROlIzCAPQtsQF0DAAWOb8ntuKCzX2AJdj), MetricRecord(metric=HttpStatusCode, value=200), MetricRecord(metric=BackoffDelayDuration, value=PT0S), MetricRecord(metric=TimeToLastByte, value=PT0.148915667S), MetricRecord(metric=AwsRequestId, value=78AW9BM7SWR6YMGB)], children=[MetricCollection(name=HttpClient, metrics=[MetricRecord(metric=MaxConcurrency, value=50), MetricRecord(metric=AvailableConcurrency, value=0), MetricRecord(metric=LeasedConcurrency, value=1), MetricRecord(metric=ConcurrencyAcquireDuration, value=PT0.002623S), MetricRecord(metric=PendingConcurrencyAcquires, value=0), MetricRecord(metric=HttpClientName, value=Apache)], children=[])])]) INFO LoggingMetricPublisher - [4e6f2bb5] ApiCall INFO LoggingMetricPublisher - [4e6f2bb5] ┌──────────────────────────────────────────┐ INFO LoggingMetricPublisher - [4e6f2bb5] │ MarshallingDuration=PT0.000063S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ RetryCount=0 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ApiCallSuccessful=true │ INFO LoggingMetricPublisher - [4e6f2bb5] │ OperationName=ListBuckets │ INFO LoggingMetricPublisher - [4e6f2bb5] │ EndpointResolveDuration=PT0.000024375S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ApiCallDuration=PT0.018463083S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ CredentialsFetchDuration=PT0.000022334S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ServiceEndpoint=https://s3.amazonaws.com │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ServiceId=S3 │ INFO LoggingMetricPublisher - [4e6f2bb5] └──────────────────────────────────────────┘ INFO LoggingMetricPublisher - [4e6f2bb5] ApiCallAttempt INFO LoggingMetricPublisher - [4e6f2bb5] ┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ INFO LoggingMetricPublisher - [4e6f2bb5] │ TimeToFirstByte=PT0.0165575S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ SigningDuration=PT0.000301125S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ReadThroughput=1195591.792850103 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ServiceCallDuration=PT0.0165575S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ AwsExtendedRequestId=3QI1eenRuokdszWqZBmBMDUmko6FlSmHkM+CUMNMeLor7gJml4D4lv6QXUZ1zWoTgG+tHbr6yo2vHdz4h1P8PDovvtMFRCeB │ INFO LoggingMetricPublisher - [4e6f2bb5] │ HttpStatusCode=200 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ BackoffDelayDuration=PT0S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ TimeToLastByte=PT0.017952625S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ AwsRequestId=78AVFAF795AAWAXH │ INFO LoggingMetricPublisher - [4e6f2bb5] └───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ INFO LoggingMetricPublisher - [4e6f2bb5] HttpClient INFO LoggingMetricPublisher - [4e6f2bb5] ┌───────────────────────────────────────┐ INFO LoggingMetricPublisher - [4e6f2bb5] │ MaxConcurrency=50 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ AvailableConcurrency=0 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ LeasedConcurrency=1 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ ConcurrencyAcquireDuration=PT0.00004S │ INFO LoggingMetricPublisher - [4e6f2bb5] │ PendingConcurrencyAcquires=0 │ INFO LoggingMetricPublisher - [4e6f2bb5] │ HttpClientName=Apache │ INFO LoggingMetricPublisher - [4e6f2bb5] └───────────────────────────────────────┘ INFO S3LoggingMetricPublisherDemo - Found 6 buckets in your AWS account.

Maven 文件 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>s3-logging-metric-publisher-demo</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>AWS S3 LoggingMetricPublisher Demo</name> <description>Demonstrates how to use LoggingMetricPublisher with AWS S3 SDK for Java 2.x</description> <properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <aws.java.sdk.version>2.31.66</aws.java.sdk.version> <log4j.version>2.24.3</log4j.version> </properties> <dependencyManagement> <dependencies> <!-- AWS SDK BOM for dependency management --> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>${aws.java.sdk.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- Log4j BOM for logging dependency management --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-bom</artifactId> <version>${log4j.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- AWS S3 SDK for demonstration --> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> </dependency> <!-- Log4j2 SLF4J implementation --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j2-impl</artifactId> </dependency> <!-- Log4j2 Core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.13.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>

Log4j2.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="ConsoleAppender" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </Console> </Appenders> <Loggers> <Root level="INFO"> <AppenderRef ref="ConsoleAppender"/> </Root> <!-- Ensure LoggingMetricPublisher output appears. --> <Logger name="software.amazon.awssdk.metrics.LoggingMetricPublisher" level="INFO"/> </Loggers> </Configuration>

这些指标包括计时信息、服务详细信息、操作名称和 HTTP 状态代码,可帮助您了解应用程序的 AWS API 使用模式。

后续步骤

LoggingMetricPublisher用于开发和调试之后,请考虑生产环境中的以下选项: