From 457609bdddb67507ee4ac652336af0a2ff94a344 Mon Sep 17 00:00:00 2001 From: Alan Zimmer <48699787+alzimmermsft@users.noreply.github.com> Date: Tue, 1 Mar 2022 18:11:23 -0500 Subject: [PATCH] Use More Static Loggers in Core Libraries (#27339) Use Static Loggers in Core Libraries --- .../checkstyle/checks/GoodLoggingCheck.java | 35 +------------------ .../checks/GoodLoggerCheckTest.java | 8 ----- .../com/azure/core/amqp/AmqpRetryOptions.java | 10 +++--- .../com/azure/core/amqp/ProxyOptions.java | 4 +-- .../ActiveClientTokenManager.java | 30 ++++++++-------- .../implementation/AmqpExceptionHandler.java | 6 ++-- .../AzureTokenManagerProvider.java | 6 ++-- .../implementation/ConnectionOptions.java | 4 ++- .../ConnectionStringProperties.java | 6 ++-- .../ReactorHandlerProvider.java | 10 +++--- .../amqp/implementation/ReactorProvider.java | 4 +-- .../amqp/implementation/TracerProvider.java | 4 +-- .../TransactionCoordinator.java | 6 ++-- .../handler/DispatchHandler.java | 2 -- .../handler/StrictTlsContextSpi.java | 4 +-- .../core/amqp/models/AmqpMessageBody.java | 10 +++--- .../models/TransactionalDeliveryOutcome.java | 5 +-- .../jdk/httpclient/JdkAsyncHttpClient.java | 18 +++++----- .../httpclient/JdkAsyncHttpClientBuilder.java | 4 +-- .../netty/NettyAsyncHttpClientBuilder.java | 16 ++++----- .../implementation/HttpProxyHandler.java | 7 ++-- .../implementation/ProxyAuthenticator.java | 4 +-- .../avro/apache/ApacheAvroSerializer.java | 6 ++-- .../json/gson/GsonJsonSerializer.java | 4 +-- .../json/jackson/JacksonJsonSerializer.java | 10 +++--- .../opentelemetry/OpenTelemetryTracer.java | 12 +++---- .../core/credential/AzureKeyCredential.java | 7 ++-- .../credential/AzureNamedKeyCredential.java | 7 ++-- .../core/credential/AzureSasCredential.java | 7 ++-- .../BasicAuthenticationCredential.java | 28 ++++----------- .../core/credential/SimpleTokenCache.java | 7 ++-- .../azure/core/http/HttpAuthorization.java | 8 +++-- .../java/com/azure/core/http/HttpRange.java | 8 +++-- .../java/com/azure/core/http/HttpRequest.java | 11 +++--- .../http/policy/AzureKeyCredentialPolicy.java | 5 +-- .../azure/core/http/policy/CookiePolicy.java | 4 +-- .../http/policy/DefaultRedirectStrategy.java | 18 +++++----- .../core/http/policy/ExponentialBackoff.java | 12 +++---- .../azure/core/http/policy/FixedDelay.java | 5 +-- .../azure/core/http/policy/HostPolicy.java | 5 +-- .../core/http/policy/HttpLogOptions.java | 7 ++-- .../core/http/policy/HttpLoggingPolicy.java | 35 ++++++++++++++----- .../azure/core/http/policy/PortPolicy.java | 5 +-- .../core/http/policy/ProtocolPolicy.java | 5 +-- .../azure/core/http/policy/RetryPolicy.java | 11 +++--- .../azure/core/http/rest/PercentEscaper.java | 14 ++++---- .../http/rest/ResponseConstructorsCache.java | 14 ++++---- .../com/azure/core/http/rest/RestProxy.java | 10 +++--- .../core/implementation/AccessTokenCache.java | 9 ++--- .../implementation/ByteBufferCollector.java | 7 ++-- .../implementation/FileWriteSubscriber.java | 5 +-- .../http/BufferedHttpResponse.java | 9 ++--- .../jackson/FlatteningSerializer.java | 7 ++-- .../jackson/JacksonVersion.java | 11 +++--- .../jackson/ObjectMapperFactory.java | 9 ++--- .../serializer/DefaultJsonSerializer.java | 12 ++++--- .../serializer/HttpResponseBodyDecoder.java | 6 ++-- .../java/com/azure/core/models/GeoArray.java | 21 +++++------ .../com/azure/core/models/GeoBoundingBox.java | 7 ++-- .../com/azure/core/models/GeoLinearRing.java | 8 +++-- .../com/azure/core/models/GeoPosition.java | 7 ++-- .../azure/core/models/JsonPatchDocument.java | 5 +-- .../com/azure/core/util/ClientOptions.java | 7 ++-- .../java/com/azure/core/util/CoreUtils.java | 5 +-- .../azure/core/util/HttpClientOptions.java | 15 ++++---- .../ContinuablePagedByItemIterable.java | 5 ++- .../ContinuablePagedByPageIterable.java | 5 ++- .../util/paging/ContinuablePagedFluxCore.java | 5 +-- .../core/util/polling/AsyncPollResponse.java | 9 ++--- .../util/polling/ChainedPollingStrategy.java | 4 +-- .../core/util/polling/DefaultSyncPoller.java | 8 ++--- .../util/polling/LocationPollingStrategy.java | 4 +-- .../azure/core/util/polling/PollerFlux.java | 12 +++---- .../core/util/polling/PollingContext.java | 8 ++--- 74 files changed, 341 insertions(+), 337 deletions(-) diff --git a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/GoodLoggingCheck.java b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/GoodLoggingCheck.java index ee2bff71ad6b8..5eef8042d3182 100644 --- a/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/GoodLoggingCheck.java +++ b/eng/code-quality-reports/src/main/java/com/azure/tools/checkstyle/checks/GoodLoggingCheck.java @@ -38,8 +38,7 @@ public class GoodLoggingCheck extends AbstractCheck { TokenTypes.CLASS_DEF, TokenTypes.LITERAL_NEW, TokenTypes.VARIABLE_DEF, - TokenTypes.METHOD_CALL, - TokenTypes.METHOD_DEF + TokenTypes.METHOD_CALL }; static final String STATIC_LOGGER_ERROR = "Use a static ClientLogger instance in a static method."; @@ -117,9 +116,6 @@ public void visitToken(DetailAST ast) { log(ast, String.format(NOT_CLIENT_LOGGER_ERROR, "Java System", CLIENT_LOGGER_PATH, methodCallName)); } break; - case TokenTypes.METHOD_DEF: - checkForInvalidStaticLoggerUsage(ast); - break; default: // Checkstyle complains if there's no default block in switch break; @@ -185,33 +181,4 @@ private void checkLoggerNameMatch(DetailAST varToken) { log(varToken, String.format(LOGGER_NAME_ERROR, LOGGER, identAST.getText())); } } - - /** - * Report error if a static ClientLogger instance used in a non-static method. - * - * @param methodDefToken METHOD_DEF AST node - */ - private void checkForInvalidStaticLoggerUsage(DetailAST methodDefToken) { - - // if not a static method - if (!(TokenUtil.findFirstTokenByPredicate(methodDefToken, - node -> node.branchContains(TokenTypes.LITERAL_STATIC)).isPresent())) { - - // error if static `LOGGER` present, LOGGER.* - if (methodDefToken.findFirstToken(TokenTypes.SLIST) != null) { - TokenUtil.forEachChild(methodDefToken.findFirstToken(TokenTypes.SLIST), TokenTypes.EXPR, exprToken -> { - if (exprToken != null) { - DetailAST methodCallToken = exprToken.findFirstToken(TokenTypes.METHOD_CALL); - if (methodCallToken != null && methodCallToken.findFirstToken(TokenTypes.DOT) != null) { - if (methodCallToken.findFirstToken(TokenTypes.DOT) - .findFirstToken(TokenTypes.IDENT).getText().equals(LOGGER.toUpperCase())) { - log(methodDefToken, STATIC_LOGGER_ERROR); - } - } - } - }); - } - } - } - } diff --git a/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/GoodLoggerCheckTest.java b/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/GoodLoggerCheckTest.java index 7ba21af34016e..11472df110870 100644 --- a/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/GoodLoggerCheckTest.java +++ b/eng/code-quality-reports/src/test/java/com/azure/tools/checkstyle/checks/GoodLoggerCheckTest.java @@ -56,14 +56,6 @@ public void invalidLoggerNameTestData() throws Exception { verify(checker, getPath("InvalidLoggerNameTestData.java"), expected); } - @Test - public void nonStaticLoggerTestData() throws Exception { - String[] expected = { - expectedErrorMessage(9, 5, STATIC_LOGGER_ERROR) - }; - verify(checker, getPath("NonStaticLoggerTestData.java"), expected); - } - @Test public void wrongClassInLoggerConstructorTestData() throws Exception { String[] expected = { diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryOptions.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryOptions.java index 355557e9b45e4..d63bd8d6a0a5d 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryOptions.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryOptions.java @@ -14,7 +14,7 @@ */ @Fluent public class AmqpRetryOptions { - private final ClientLogger logger = new ClientLogger(AmqpRetryOptions.class); + private static final ClientLogger LOGGER = new ClientLogger(AmqpRetryOptions.class); private int maxRetries; private Duration delay; @@ -69,7 +69,7 @@ public AmqpRetryOptions setMode(AmqpRetryMode retryMode) { */ public AmqpRetryOptions setMaxRetries(int numberOfRetries) { if (numberOfRetries < 0) { - throw logger.logExceptionAsError(new IllegalArgumentException("'numberOfRetries' cannot be negative.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'numberOfRetries' cannot be negative.")); } this.maxRetries = numberOfRetries; @@ -88,7 +88,7 @@ public AmqpRetryOptions setMaxRetries(int numberOfRetries) { public AmqpRetryOptions setDelay(Duration delay) { Objects.requireNonNull(delay, "'delay' cannot be null."); if (delay.isNegative() || delay.isZero()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'delay' must be positive.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'delay' must be positive.")); } this.delay = delay; @@ -107,7 +107,7 @@ public AmqpRetryOptions setDelay(Duration delay) { public AmqpRetryOptions setMaxDelay(Duration maximumDelay) { Objects.requireNonNull(maximumDelay, "'maximumDelay' cannot be null."); if (maximumDelay.isNegative() || maximumDelay.isZero()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'maximumDelay' must be positive.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maximumDelay' must be positive.")); } this.maxDelay = maximumDelay; @@ -126,7 +126,7 @@ public AmqpRetryOptions setMaxDelay(Duration maximumDelay) { public AmqpRetryOptions setTryTimeout(Duration tryTimeout) { Objects.requireNonNull(tryTimeout, "'tryTimeout' cannot be null"); if (tryTimeout.isNegative() || tryTimeout.isZero()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'tryTimeout' must be positive.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tryTimeout' must be positive.")); } this.tryTimeout = tryTimeout; diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ProxyOptions.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ProxyOptions.java index 90a4fffb4c6e9..9f63c9f5693e4 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ProxyOptions.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/ProxyOptions.java @@ -25,7 +25,7 @@ public class ProxyOptions implements AutoCloseable { */ public static final String PROXY_PASSWORD = "PROXY_PASSWORD"; - private final ClientLogger logger = new ClientLogger(ProxyOptions.class); + private static final ClientLogger LOGGER = new ClientLogger(ProxyOptions.class); private final PasswordAuthentication credentials; private final Proxy proxyAddress; private final ProxyAuthenticationType authentication; @@ -62,7 +62,7 @@ public ProxyOptions(ProxyAuthenticationType authentication, Proxy proxyAddress, if (username != null && password != null) { this.credentials = new PasswordAuthentication(username, password.toCharArray()); } else { - logger.info("Username or password is null. Using system-wide authentication."); + LOGGER.info("Username or password is null. Using system-wide authentication."); this.credentials = null; } } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java index 10bbf7cac11ce..e1b3c9705d399 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java @@ -26,7 +26,7 @@ * Manages the re-authorization of the client to the token audience against the CBS node. */ public class ActiveClientTokenManager implements TokenManager { - private final ClientLogger logger = new ClientLogger(ActiveClientTokenManager.class); + private static final ClientLogger LOGGER = new ClientLogger(ActiveClientTokenManager.class); private final AtomicBoolean hasScheduled = new AtomicBoolean(); private final AtomicBoolean hasDisposed = new AtomicBoolean(); private final Mono cbsNode; @@ -79,14 +79,14 @@ public Mono authorize() { // If this is the first time authorize is called, the task will not have been scheduled yet. if (!hasScheduled.getAndSet(true)) { - logger.atInfo() + LOGGER.atInfo() .addKeyValue("scopes", scopes) .log("Scheduling refresh token task."); final Duration firstInterval = Duration.ofMillis(refreshIntervalMS); lastRefreshInterval.set(firstInterval); authorizationResults.emitNext(AmqpResponseCode.ACCEPTED, (signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult).log("Could not emit ACCEPTED."); + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult).log("Could not emit ACCEPTED."); return false; }); @@ -104,12 +104,12 @@ public void close() { } authorizationResults.emitComplete((signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult).log("Could not close authorizationResults."); + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult).log("Could not close authorizationResults."); return false; }); durationSource.emitComplete((signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult).log("Could not close durationSource."); + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult).log("Could not close durationSource."); return false; }); @@ -122,7 +122,7 @@ public void close() { private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { // EmitterProcessor can queue up an initial refresh interval before any subscribers are received. durationSource.emitNext(initialRefresh, (signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult).log("Could not emit initial refresh interval."); + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult).log("Could not emit initial refresh interval."); return false; }); @@ -131,7 +131,7 @@ private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { .takeUntil(duration -> hasDisposed.get()) .flatMap(delay -> { - logger.atInfo() + LOGGER.atInfo() .addKeyValue("scopes", scopes) .log("Refreshing token."); @@ -142,13 +142,13 @@ private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { (amqpException, interval) -> { final Duration lastRefresh = lastRefreshInterval.get(); - logger.atError() + LOGGER.atError() .addKeyValue("scopes", scopes) .addKeyValue(INTERVAL_KEY, interval) .log("Error is transient. Rescheduling authorization task.", amqpException); durationSource.emitNext(lastRefresh, (signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult) .addKeyValue("lastRefresh", lastRefresh) .log("Could not emit lastRefresh."); @@ -156,13 +156,13 @@ private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { }); }) .subscribe(interval -> { - logger.atVerbose() + LOGGER.atVerbose() .addKeyValue("scopes", scopes) .addKeyValue(INTERVAL_KEY, interval) .log("Authorization successful. Refreshing token."); authorizationResults.emitNext(AmqpResponseCode.ACCEPTED, (signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult) .log("Could not emit ACCEPTED after refresh."); return false; }); @@ -171,14 +171,14 @@ private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { lastRefreshInterval.set(nextRefresh); durationSource.emitNext(nextRefresh, (signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult) .addKeyValue("nextRefresh", nextRefresh) .log("Could not emit nextRefresh."); return false; }); }, error -> { - logger.atError() + LOGGER.atError() .addKeyValue("scopes", scopes) .addKeyValue("audience", tokenAudience) .log("Error occurred while refreshing token that is not retriable. Not scheduling" @@ -188,14 +188,14 @@ private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { if (!hasDisposed.getAndSet(true)) { hasScheduled.set(false); durationSource.emitComplete((signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult) .log("Could not close durationSource."); return false; }); authorizationResults.emitError(error, (signalType, emitResult) -> { - addSignalTypeAndResult(logger.atVerbose(), signalType, emitResult) + addSignalTypeAndResult(LOGGER.atVerbose(), signalType, emitResult) .log("Could not emit authorization error.", error); return false; diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpExceptionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpExceptionHandler.java index a8c61303cb1f2..1c120a5e08a84 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpExceptionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AmqpExceptionHandler.java @@ -12,7 +12,7 @@ * Handles exceptions generated by AMQP connections, sessions, and/or links. */ abstract class AmqpExceptionHandler { - private final ClientLogger logger = new ClientLogger(AmqpExceptionHandler.class); + private static final ClientLogger LOGGER = new ClientLogger(AmqpExceptionHandler.class); /** * Creates a new instance of the exception handler. @@ -26,7 +26,7 @@ abstract class AmqpExceptionHandler { * @param exception The exception that caused the connection error. */ void onConnectionError(Throwable exception) { - logger.warning("Connection exception encountered.", exception); + LOGGER.warning("Connection exception encountered.", exception); } /** @@ -35,6 +35,6 @@ void onConnectionError(Throwable exception) { * @param shutdownSignal The shutdown signal that was received. */ void onConnectionShutdown(AmqpShutdownSignal shutdownSignal) { - addShutdownSignal(logger.atInfo(), shutdownSignal).log("Shutdown received"); + addShutdownSignal(LOGGER.atInfo(), shutdownSignal).log("Shutdown received"); } } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java index 9a015af447f8b..9b8ca13ff73c3 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java @@ -17,7 +17,7 @@ public class AzureTokenManagerProvider implements TokenManagerProvider { static final String TOKEN_AUDIENCE_FORMAT = "amqp://%s/%s"; - private final ClientLogger logger = new ClientLogger(AzureTokenManagerProvider.class); + private static final ClientLogger LOGGER = new ClientLogger(AzureTokenManagerProvider.class); private final CbsAuthorizationType authorizationType; private final String fullyQualifiedNamespace; private final String activeDirectoryScope; @@ -48,7 +48,7 @@ public TokenManager getTokenManager(Mono cbsNodeMono, S final String scopes = getScopesFromResource(resource); final String tokenAudience = String.format(Locale.US, TOKEN_AUDIENCE_FORMAT, fullyQualifiedNamespace, resource); - logger.atVerbose() + LOGGER.atVerbose() .addKeyValue("audience", tokenAudience) .addKeyValue("resource", resource) .log("Creating new token manager."); @@ -66,7 +66,7 @@ public String getScopesFromResource(String resource) { } else if (CbsAuthorizationType.SHARED_ACCESS_SIGNATURE.equals(authorizationType)) { return String.format(Locale.US, TOKEN_AUDIENCE_FORMAT, fullyQualifiedNamespace, resource); } else { - throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, + throw LOGGER.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "'%s' is not supported authorization type for token audience.", authorizationType))); } } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionOptions.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionOptions.java index f6a74799caf43..00488c5a1e83f 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionOptions.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionOptions.java @@ -23,6 +23,8 @@ */ @Immutable public class ConnectionOptions { + private static final ClientLogger LOGGER = new ClientLogger(ConnectionOptions.class); + private final TokenCredential tokenCredential; private final AmqpTransportType transport; private final AmqpRetryOptions retryOptions; @@ -243,7 +245,7 @@ private static int getPort(AmqpTransportType transport) { case AMQP_WEB_SOCKETS: return WebSocketsConnectionHandler.HTTPS_PORT; default: - throw new ClientLogger(ConnectionOptions.class).logThrowableAsError( + throw LOGGER.logThrowableAsError( new IllegalArgumentException("Transport Type is not supported: " + transport)); } } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionStringProperties.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionStringProperties.java index 6ceb2b563e373..aef0b9e61a396 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionStringProperties.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ConnectionStringProperties.java @@ -15,7 +15,7 @@ * The set of properties that comprise a connection string from the Azure portal. */ public class ConnectionStringProperties { - private final ClientLogger logger = new ClientLogger(ConnectionStringProperties.class); + private static final ClientLogger LOGGER = new ClientLogger(ConnectionStringProperties.class); private static final String TOKEN_VALUE_SEPARATOR = "="; private static final String ENDPOINT_SCHEME_SB_PREFIX = "sb://"; @@ -105,7 +105,7 @@ public ConnectionStringProperties(String connectionString) { if (endpoint == null || (includesSharedKey && includesSharedAccessSignature) // includes both SAS and key or value || (!hasSharedKeyAndValue && !includesSharedAccessSignature)) { // invalid key, value and SAS - throw logger.logExceptionAsError(new IllegalArgumentException(ERROR_MESSAGE_FORMAT)); + throw LOGGER.logExceptionAsError(new IllegalArgumentException(ERROR_MESSAGE_FORMAT)); } this.endpoint = endpoint; @@ -163,7 +163,7 @@ public String getSharedAccessSignature() { private String validateAndUpdateDefaultScheme(final String endpoint) { if (CoreUtils.isNullOrEmpty(endpoint)) { - throw logger.logExceptionAsError(new IllegalArgumentException( + throw LOGGER.logExceptionAsError(new IllegalArgumentException( "'Endpoint' must be provided in 'connectionString'.")); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java index cd78028c99b66..d44a5a8f81092 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java @@ -24,7 +24,7 @@ * Provides handlers for the various types of links. */ public class ReactorHandlerProvider { - private final ClientLogger logger = new ClientLogger(ReactorHandlerProvider.class); + private static final ClientLogger LOGGER = new ClientLogger(ReactorHandlerProvider.class); private final ReactorProvider provider; /** @@ -60,7 +60,7 @@ public ConnectionHandler createConnectionHandler(String connectionId, Connection } if (options.getTransportType() != AmqpTransportType.AMQP_WEB_SOCKETS) { - throw logger.logExceptionAsWarning(new IllegalArgumentException(String.format(Locale.US, + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException(String.format(Locale.US, "This transport type '%s' is not supported.", options.getTransportType()))); } @@ -72,21 +72,21 @@ public ConnectionHandler createConnectionHandler(String connectionId, Connection // TODO (conniey): See if we this is supported later on. if (isCustomEndpointConfigured && (isUserProxyConfigured || isSystemProxyConfigured)) { - throw logger.logExceptionAsError(new UnsupportedOperationException(String.format( + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(String.format( "Unable to proxy connection to custom endpoint. Custom endpoint: %s. Proxy settings: %s. " + "Namespace: %s", options.getHostname(), options.getProxyOptions().getProxyAddress(), options.getFullyQualifiedNamespace()))); } if (isUserProxyConfigured) { - logger.info("Using user configured proxy to connect to: '{}:{}'. Proxy: {}", + LOGGER.info("Using user configured proxy to connect to: '{}:{}'. Proxy: {}", options.getFullyQualifiedNamespace(), options.getPort(), options.getProxyOptions().getProxyAddress()); final SslPeerDetails peerDetails = Proton.sslPeerDetails(options.getHostname(), options.getPort()); return new WebSocketsProxyConnectionHandler(connectionId, options, options.getProxyOptions(), peerDetails); } else if (isSystemProxyConfigured) { - logger.info("System default proxy configured for hostname:port '{}:{}'. Using proxy.", + LOGGER.info("System default proxy configured for hostname:port '{}:{}'. Using proxy.", options.getFullyQualifiedNamespace(), options.getPort()); final SslPeerDetails peerDetails = Proton.sslPeerDetails(options.getHostname(), options.getPort()); diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorProvider.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorProvider.java index d7c3529857904..5254f9864c6f5 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorProvider.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorProvider.java @@ -14,7 +14,7 @@ import java.nio.channels.Pipe; public class ReactorProvider { - private final ClientLogger logger = new ClientLogger(ReactorProvider.class); + private static final ClientLogger LOGGER = new ClientLogger(ReactorProvider.class); private final Object lock = new Object(); private Reactor reactor; private ReactorDispatcher reactorDispatcher; @@ -48,7 +48,7 @@ public Reactor createReactor(String connectionId, int maxFrameSize) throws IOExc } if (maxFrameSize <= 0) { - throw logger.logExceptionAsError(new IllegalArgumentException("'maxFrameSize' must be a positive number.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'maxFrameSize' must be a positive number.")); } final ReactorOptions reactorOptions = new ReactorOptions(); diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TracerProvider.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TracerProvider.java index 295c531dec53f..d697d3f083516 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TracerProvider.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TracerProvider.java @@ -12,7 +12,7 @@ import java.util.Objects; public class TracerProvider { - private final ClientLogger logger = new ClientLogger(TracerProvider.class); + private static final ClientLogger LOGGER = new ClientLogger(TracerProvider.class); private Tracer tracer; public TracerProvider(Iterable tracers) { @@ -146,7 +146,7 @@ private String getSpanName(String serviceBaseName, ProcessKind processKind) { serviceBaseName += "process"; break; default: - logger.warning("Unknown processKind type: {}", processKind); + LOGGER.warning("Unknown processKind type: {}", processKind); break; } return serviceBaseName; diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TransactionCoordinator.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TransactionCoordinator.java index 65f8d8ac0a88c..d4a50384808b1 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TransactionCoordinator.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/TransactionCoordinator.java @@ -24,7 +24,7 @@ */ final class TransactionCoordinator implements AmqpTransactionCoordinator { - private final ClientLogger logger = new ClientLogger(TransactionCoordinator.class); + private static final ClientLogger LOGGER = new ClientLogger(TransactionCoordinator.class); private final AmqpSendLink sendLink; private final MessageSerializer messageSerializer; @@ -66,7 +66,7 @@ public Mono discharge(AmqpTransaction transaction, boolean isCommit) { break; default: sink.error(new IllegalArgumentException("Expected a Accepted, received: " + outcome)); - logger.warning("Unknown DeliveryState type: {}", stateType); + LOGGER.warning("Unknown DeliveryState type: {}", stateType); } }); } @@ -100,7 +100,7 @@ public Mono declare() { break; default: sink.error(new IllegalArgumentException("Expected a Declared, received: " + outcome)); - logger.warning("Unknown DeliveryState type: {}", stateType); + LOGGER.warning("Unknown DeliveryState type: {}", stateType); } }); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/DispatchHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/DispatchHandler.java index 6c7053c41aec2..4419f012f27e1 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/DispatchHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/DispatchHandler.java @@ -3,7 +3,6 @@ package com.azure.core.amqp.implementation.handler; -import com.azure.core.util.logging.ClientLogger; import org.apache.qpid.proton.engine.BaseHandler; import org.apache.qpid.proton.engine.Event; import org.apache.qpid.proton.reactor.Reactor; @@ -14,7 +13,6 @@ * Base class that executes work on reactor. */ public class DispatchHandler extends BaseHandler { - private final ClientLogger logger = new ClientLogger(DispatchHandler.class); private final Runnable work; /** diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/StrictTlsContextSpi.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/StrictTlsContextSpi.java index 33e1b229cc5f8..89396bd99f2d9 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/StrictTlsContextSpi.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/StrictTlsContextSpi.java @@ -24,7 +24,7 @@ class StrictTlsContextSpi extends SSLContextSpi { private static final String SSL_V2_HELLO = "SSLv2Hello"; - private final ClientLogger logger = new ClientLogger(StrictTlsContextSpi.class); + private static final ClientLogger LOGGER = new ClientLogger(StrictTlsContextSpi.class); private final SSLContext sslContext; /** @@ -106,7 +106,7 @@ private String[] getAllowedProtocols(String[] protocols) { .filter(protocol -> { final boolean isSSLv2Hello = protocol.equalsIgnoreCase(SSL_V2_HELLO); if (isSSLv2Hello) { - logger.info("{} was an enabled protocol. Filtering out.", SSL_V2_HELLO); + LOGGER.info("{} was an enabled protocol. Filtering out.", SSL_V2_HELLO); } return !isSSLv2Hello; diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/AmqpMessageBody.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/AmqpMessageBody.java index 71a36b1ea1f93..7d60096a264c0 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/AmqpMessageBody.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/AmqpMessageBody.java @@ -51,7 +51,7 @@ * */ public final class AmqpMessageBody { - private final ClientLogger logger = new ClientLogger(AmqpMessageBody.class); + private static final ClientLogger LOGGER = new ClientLogger(AmqpMessageBody.class); private AmqpMessageBodyType bodyType; // We expect user to call `getFirstData()` more because we support one byte[] as present. @@ -192,7 +192,7 @@ public AmqpMessageBodyType getBodyType() { */ public IterableStream getData() { if (bodyType != AmqpMessageBodyType.DATA) { - throw logger.logExceptionAsError(new IllegalArgumentException( + throw LOGGER.logExceptionAsError(new IllegalArgumentException( "This method can only be called if AMQP Message body type is 'DATA'.")); } if (dataList == null) { @@ -239,7 +239,7 @@ public IterableStream getData() { */ public byte[] getFirstData() { if (bodyType != AmqpMessageBodyType.DATA) { - throw logger.logExceptionAsError(new IllegalArgumentException( + throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can be called if AMQP Message body type is 'DATA'. " + "The actual type is [%s].", bodyType))); } @@ -288,7 +288,7 @@ public byte[] getFirstData() { */ public List getSequence() { if (bodyType != AmqpMessageBodyType.SEQUENCE) { - throw logger.logExceptionAsError(new IllegalArgumentException( + throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can be called if AMQP Message body type is 'SEQUENCE'. " + "The actual type is [%s].", bodyType))); } @@ -336,7 +336,7 @@ public List getSequence() { */ public Object getValue() { if (bodyType != AmqpMessageBodyType.VALUE) { - throw logger.logExceptionAsError(new IllegalArgumentException( + throw LOGGER.logExceptionAsError(new IllegalArgumentException( String.format(Locale.US, "This method can be called if AMQP Message body type is 'VALUE'. " + "The actual type is [%s].", bodyType))); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/TransactionalDeliveryOutcome.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/TransactionalDeliveryOutcome.java index 9d342fcc5e755..8d8835ed477e1 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/TransactionalDeliveryOutcome.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/models/TransactionalDeliveryOutcome.java @@ -18,8 +18,9 @@ */ @Fluent public final class TransactionalDeliveryOutcome extends DeliveryOutcome { + private static final ClientLogger LOGGER = new ClientLogger(TransactionalDeliveryOutcome.class); + private final AmqpTransaction amqpTransaction; - private final ClientLogger logger = new ClientLogger(TransactionalDeliveryOutcome.class); private DeliveryOutcome outcome; /** @@ -63,7 +64,7 @@ public DeliveryOutcome getOutcome() { */ public TransactionalDeliveryOutcome setOutcome(DeliveryOutcome outcome) { if (outcome instanceof TransactionalDeliveryOutcome) { - throw logger.logExceptionAsError( + throw LOGGER.logExceptionAsError( new IllegalArgumentException("Cannot set the outcome as another nested transaction outcome.")); } diff --git a/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClient.java b/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClient.java index bc91fe9a0cedb..e3fe1a5d2f53c 100644 --- a/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClient.java +++ b/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClient.java @@ -33,7 +33,7 @@ * HttpClient implementation for the JDK HttpClient. */ class JdkAsyncHttpClient implements HttpClient { - private final ClientLogger logger = new ClientLogger(JdkAsyncHttpClient.class); + private static final ClientLogger LOGGER = new ClientLogger(JdkAsyncHttpClient.class); private final java.net.http.HttpClient jdkHttpClient; @@ -43,12 +43,12 @@ class JdkAsyncHttpClient implements HttpClient { this.jdkHttpClient = httpClient; int javaVersion = getJavaVersion(); if (javaVersion <= 11) { - throw logger.logExceptionAsError( + throw LOGGER.logExceptionAsError( new UnsupportedOperationException("JdkAsyncHttpClient is not supported in Java version 11 and below.")); } this.restrictedHeaders = restrictedHeaders; - logger.verbose("Effective restricted headers: {}", restrictedHeaders); + LOGGER.verbose("Effective restricted headers: {}", restrictedHeaders); } @Override @@ -89,7 +89,7 @@ private Mono toJdkHttpRequest(HttpRequest request) { try { builder.uri(request.getUrl().toURI()); } catch (URISyntaxException e) { - throw logger.logExceptionAsError(Exceptions.propagate(e)); + throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } final HttpHeaders headers = request.getHeaders(); if (headers != null) { @@ -98,7 +98,7 @@ private Mono toJdkHttpRequest(HttpRequest request) { if (!restrictedHeaders.contains(headerName)) { header.getValuesList().forEach(headerValue -> builder.header(headerName, headerValue)); } else { - logger.warning("The header '" + headerName + "' is restricted by default in JDK HttpClient 12 " + LOGGER.warning("The header '" + headerName + "' is restricted by default in JDK HttpClient 12 " + "and above. This header can be added to allow list in JAVA_HOME/conf/net.properties " + "or in System.setProperty() or in Configuration. Use the key 'jdk.httpclient" + ".allowRestrictedHeaders' and a comma separated list of header names."); @@ -152,16 +152,16 @@ private int getJavaVersion() { // 9 and above: 12, 14.1.1 String version = System.getProperty("java.version"); if (CoreUtils.isNullOrEmpty(version)) { - throw logger.logExceptionAsError(new RuntimeException("Can't find 'java.version' system property.")); + throw LOGGER.logExceptionAsError(new RuntimeException("Can't find 'java.version' system property.")); } if (version.startsWith("1.")) { if (version.length() < 3) { - throw logger.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version)); + throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version)); } try { return Integer.parseInt(version.substring(2, 3)); } catch (Throwable t) { - throw logger.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t)); + throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t)); } } else { int idx = version.indexOf("."); @@ -172,7 +172,7 @@ private int getJavaVersion() { try { return Integer.parseInt(version.substring(0, idx)); } catch (Throwable t) { - throw logger.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t)); + throw LOGGER.logExceptionAsError(new RuntimeException("Can't parse 'java.version':" + version, t)); } } } diff --git a/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClientBuilder.java b/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClientBuilder.java index e4b24d6c6a523..9af480b15c0a8 100644 --- a/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClientBuilder.java +++ b/sdk/core/azure-core-http-jdk-httpclient/src/main/java/com/azure/core/http/jdk/httpclient/JdkAsyncHttpClientBuilder.java @@ -55,7 +55,7 @@ public class JdkAsyncHttpClientBuilder { DEFAULT_RESTRICTED_HEADERS = Collections.unmodifiableSet(treeSet); } - private final ClientLogger logger = new ClientLogger(JdkAsyncHttpClientBuilder.class); + private static final ClientLogger LOGGER = new ClientLogger(JdkAsyncHttpClientBuilder.class); private java.net.http.HttpClient.Builder httpClientBuilder; private Duration connectionTimeout; @@ -241,7 +241,7 @@ Properties getNetworkProperties() { try (Reader reader = Files.newBufferedReader(path)) { properties.load(reader); } catch (IOException e) { - logger.warning("Cannot read net properties file at path {}", path, e); + LOGGER.warning("Cannot read net properties file at path {}", path, e); } return properties; } diff --git a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java index 57623c588ccdc..a3b45268772cc 100644 --- a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java +++ b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/NettyAsyncHttpClientBuilder.java @@ -60,22 +60,22 @@ public class NettyAsyncHttpClientBuilder { private static final long DEFAULT_RESPONSE_TIMEOUT; private static final long DEFAULT_READ_TIMEOUT; + // NettyAsyncHttpClientBuilder may be instantiated many times, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(NettyAsyncHttpClientBuilder.class); + static { - ClientLogger logger = new ClientLogger(NettyAsyncHttpClientBuilder.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, - PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger).toMillis(); + PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), LOGGER).toMillis(); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, - Duration.ofSeconds(60), logger).toMillis(); + Duration.ofSeconds(60), LOGGER).toMillis(); DEFAULT_RESPONSE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, - PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, Duration.ofSeconds(60), logger).toMillis(); + PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, Duration.ofSeconds(60), LOGGER).toMillis(); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, - Duration.ofSeconds(60), logger).toMillis(); + Duration.ofSeconds(60), LOGGER).toMillis(); } - private final ClientLogger logger = new ClientLogger(NettyAsyncHttpClientBuilder.class); - private final HttpClient baseHttpClient; private ProxyOptions proxyOptions; private ConnectionProvider connectionProvider; @@ -195,7 +195,7 @@ public com.azure.core.http.HttpClient build() { }); } else { nettyHttpClient = nettyHttpClient.proxy(proxy -> - proxy.type(toReactorNettyProxyType(buildProxyOptions.getType(), logger)) + proxy.type(toReactorNettyProxyType(buildProxyOptions.getType(), LOGGER)) .address(buildProxyOptions.getAddress()) .username(buildProxyOptions.getUsername()) .password(ignored -> buildProxyOptions.getPassword()) diff --git a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/HttpProxyHandler.java b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/HttpProxyHandler.java index d8d02a1fa4400..95e699c635d21 100644 --- a/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/HttpProxyHandler.java +++ b/sdk/core/azure-core-http-netty/src/main/java/com/azure/core/http/netty/implementation/HttpProxyHandler.java @@ -88,7 +88,8 @@ public final class HttpProxyHandler extends ProxyHandler { */ private static final Supplier NO_BODY = () -> new byte[0]; - private final ClientLogger logger = new ClientLogger(HttpProxyHandler.class); + // HttpProxyHandler will be created for each network request that is using proxy, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpProxyHandler.class); private final AuthorizationChallengeHandler challengeHandler; private final AtomicReference proxyChallengeHolderReference; @@ -207,7 +208,7 @@ private String createAuthorizationHeader() { protected boolean handleResponse(ChannelHandlerContext ctx, Object o) throws ProxyConnectException { if (o instanceof HttpResponse) { if (status != null) { - throw logger.logExceptionAsWarning(new RuntimeException("Received too many responses for a request")); + throw LOGGER.logExceptionAsWarning(new RuntimeException("Received too many responses for a request")); } HttpResponse response = (HttpResponse) o; @@ -326,7 +327,7 @@ private void validateProxyAuthenticationInfoValue(String name, Map T deserialize(Object data, Supplier decoderSupplier) { try { return reader.read(null, decoderSupplier.get()); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } @@ -86,7 +86,7 @@ public void serialize(OutputStream stream, Object value) { writer.write(value, encoder); encoder.flush(); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } diff --git a/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/GsonJsonSerializer.java b/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/GsonJsonSerializer.java index 5dd3763174f42..3e9bee0d603dc 100644 --- a/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/GsonJsonSerializer.java +++ b/sdk/core/azure-core-serializer-json-gson/src/main/java/com/azure/core/serializer/json/gson/GsonJsonSerializer.java @@ -28,7 +28,7 @@ * GSON based implementation of the {@link JsonSerializer} and {@link MemberNameConverter} interfaces. */ public final class GsonJsonSerializer implements JsonSerializer, MemberNameConverter { - private final ClientLogger logger = new ClientLogger(GsonJsonSerializer.class); + private static final ClientLogger LOGGER = new ClientLogger(GsonJsonSerializer.class); private final Gson gson; @@ -63,7 +63,7 @@ public void serialize(OutputStream stream, Object value) { try { writer.flush(); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } diff --git a/sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java b/sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java index 5ca5cfb1b8c95..e3bcae2fda7d4 100644 --- a/sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java +++ b/sdk/core/azure-core-serializer-json-jackson/src/main/java/com/azure/core/serializer/json/jackson/JacksonJsonSerializer.java @@ -21,7 +21,7 @@ */ public final class JacksonJsonSerializer implements JsonSerializer, MemberNameConverter { - private final ClientLogger logger = new ClientLogger(JacksonJsonSerializer.class); + private static final ClientLogger LOGGER = new ClientLogger(JacksonJsonSerializer.class); private final ObjectMapperShim mapper; @@ -47,7 +47,7 @@ public T deserializeFromBytes(byte[] data, TypeReference typeReference) { try { return mapper.readValue(data, typeReference.getJavaType()); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } @@ -60,7 +60,7 @@ public T deserialize(InputStream stream, TypeReference typeReference) { try { return mapper.readValue(stream, typeReference.getJavaType()); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } @@ -79,7 +79,7 @@ public byte[] serializeToBytes(Object value) { try { return mapper.writeValueAsBytes(value); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } @@ -88,7 +88,7 @@ public void serialize(OutputStream stream, Object value) { try { mapper.writeValue(stream, value); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } } diff --git a/sdk/core/azure-core-tracing-opentelemetry/src/main/java/com/azure/core/tracing/opentelemetry/OpenTelemetryTracer.java b/sdk/core/azure-core-tracing-opentelemetry/src/main/java/com/azure/core/tracing/opentelemetry/OpenTelemetryTracer.java index 2849e839055c1..5153b8e1279e3 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/src/main/java/com/azure/core/tracing/opentelemetry/OpenTelemetryTracer.java +++ b/sdk/core/azure-core-tracing-opentelemetry/src/main/java/com/azure/core/tracing/opentelemetry/OpenTelemetryTracer.java @@ -62,7 +62,7 @@ public OpenTelemetryTracer() { static final String MESSAGE_BUS_DESTINATION = "message_bus.destination"; static final String PEER_ENDPOINT = "peer.address"; - private final ClientLogger logger = new ClientLogger(OpenTelemetryTracer.class); + private static final ClientLogger LOGGER = new ClientLogger(OpenTelemetryTracer.class); private static final AutoCloseable NOOP_CLOSEABLE = () -> { }; /** @@ -147,7 +147,7 @@ public void end(int responseCode, Throwable throwable, Context context) { public void setAttribute(String key, String value, Context context) { Objects.requireNonNull(context, "'context' cannot be null"); if (CoreUtils.isNullOrEmpty(value)) { - logger.verbose("Failed to set span attribute since value is null or empty."); + LOGGER.verbose("Failed to set span attribute since value is null or empty."); return; } @@ -228,7 +228,7 @@ public Context getSharedSpanBuilder(String spanName, Context context) { public AutoCloseable makeSpanCurrent(Context context) { io.opentelemetry.context.Context traceContext = getTraceContextOrDefault(context, null); if (traceContext == null) { - logger.verbose("There is no OpenTelemetry Context on the context, cannot make it current"); + LOGGER.verbose("There is no OpenTelemetry Context on the context, cannot make it current"); return NOOP_CLOSEABLE; } return traceContext.makeCurrent(); @@ -252,7 +252,7 @@ public void addEvent(String eventName, Map traceEventAttributes, Span currentSpan = getSpanOrNull(context); if (currentSpan == null) { - logger.verbose("There is no OpenTelemetry Span or Context on the context, cannot add event"); + LOGGER.verbose("There is no OpenTelemetry Span or Context on the context, cannot add event"); return; } @@ -404,7 +404,7 @@ private Attributes convertToOtelAttributes(Map attributes) { } else if (value instanceof boolean[]) { attributesBuilder.put(key, (boolean[]) value); } else { - logger.warning("Could not populate attribute with key '{}', type is not supported."); + LOGGER.warning("Could not populate attribute with key '{}', type is not supported."); } }); return attributesBuilder.build(); @@ -471,7 +471,7 @@ private void addMessagingAttributes(Span span, Context context) { private T getOrNull(Context context, String key, Class clazz) { final Optional optional = context.getData(key); final Object result = optional.filter(value -> clazz.isAssignableFrom(value.getClass())).orElseGet(() -> { - logger.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); + LOGGER.verbose("Could not extract key '{}' of type '{}' from context.", key, clazz); return null; }); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java b/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java index e14e526d73474..60083cf1e6167 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java @@ -11,7 +11,8 @@ * Represents a credential that uses a key to authenticate to an Azure Service. */ public final class AzureKeyCredential { - private final ClientLogger logger = new ClientLogger(AzureKeyCredential.class); + // AzureKeyCredential is a commonly used credential type, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AzureKeyCredential.class); private volatile String key; /** @@ -24,7 +25,7 @@ public final class AzureKeyCredential { public AzureKeyCredential(String key) { Objects.requireNonNull(key, "'key' cannot be null."); if (key.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty.")); } this.key = key; @@ -50,7 +51,7 @@ public String getKey() { public AzureKeyCredential update(String key) { Objects.requireNonNull(key, "'key' cannot be null."); if (key.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty.")); } this.key = key; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureNamedKeyCredential.java b/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureNamedKeyCredential.java index f9d810d48562d..f13c646c792f8 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureNamedKeyCredential.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureNamedKeyCredential.java @@ -25,7 +25,8 @@ * */ public final class AzureNamedKeyCredential { - private final ClientLogger logger = new ClientLogger(AzureNamedKeyCredential.class); + // AzureNamedKeyCredential is a commonly used credential type, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AzureNamedKeyCredential.class); private volatile AzureNamedKey credentials; @@ -70,10 +71,10 @@ private void validateInputParameters(String name, String key) { Objects.requireNonNull(name, "'name' cannot be null."); Objects.requireNonNull(key, "'key' cannot be null."); if (name.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty.")); } if (key.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'key' cannot be empty.")); } } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureSasCredential.java b/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureSasCredential.java index b5fc2684c549d..e555399dd754e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureSasCredential.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureSasCredential.java @@ -12,7 +12,8 @@ * Represents a credential that uses a shared access signature to authenticate to an Azure Service. */ public final class AzureSasCredential { - private final ClientLogger logger = new ClientLogger(AzureSasCredential.class); + // AzureSasCredential is a commonly used credential type, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AzureSasCredential.class); private final Function signatureEncoder; private volatile String signature; @@ -46,7 +47,7 @@ public AzureSasCredential(String signature) { public AzureSasCredential(String signature, Function signatureEncoder) { Objects.requireNonNull(signature, "'signature' cannot be null."); if (signature.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'signature' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'signature' cannot be empty.")); } this.signatureEncoder = signatureEncoder; @@ -73,7 +74,7 @@ public String getSignature() { public AzureSasCredential update(String signature) { Objects.requireNonNull(signature, "'signature' cannot be null."); if (signature.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'signature' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'signature' cannot be empty.")); } this.signature = (signatureEncoder == null) ? signature : signatureEncoder.apply(signature); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/credential/BasicAuthenticationCredential.java b/sdk/core/azure-core/src/main/java/com/azure/core/credential/BasicAuthenticationCredential.java index 318ee48502280..bb6af03506259 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/credential/BasicAuthenticationCredential.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/credential/BasicAuthenticationCredential.java @@ -4,26 +4,19 @@ package com.azure.core.credential; import com.azure.core.util.Base64Util; -import com.azure.core.util.logging.ClientLogger; import reactor.core.publisher.Mono; -import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; /** * Basic Auth credentials for use with a REST Service Client. */ public class BasicAuthenticationCredential implements TokenCredential { - private final ClientLogger logger = new ClientLogger(BasicAuthenticationCredential.class); /** - * Basic auth user name. + * Base64 encoded username-password credential. */ - private final String username; - - /** - * Basic auth password. - */ - private final String password; + private final String encodedCredential; /** * Creates a basic authentication credential. @@ -32,8 +25,8 @@ public class BasicAuthenticationCredential implements TokenCredential { * @param password basic auth password */ public BasicAuthenticationCredential(String username, String password) { - this.username = username; - this.password = password; + String credential = username + ":" + password; + this.encodedCredential = Base64Util.encodeToString(credential.getBytes(StandardCharsets.UTF_8)); } /** @@ -41,15 +34,6 @@ public BasicAuthenticationCredential(String username, String password) { */ @Override public Mono getToken(TokenRequestContext request) { - String credential = username + ":" + password; - String encodedCredential; - try { - encodedCredential = Base64Util.encodeToString(credential.getBytes("UTF8")); - } catch (UnsupportedEncodingException e) { - // The encoding is hard-coded, so if it's unsupported, it needs to be fixed right here. - throw logger.logExceptionAsError(new RuntimeException(e)); - } - - return Mono.just(new AccessToken(encodedCredential, OffsetDateTime.MAX)); + return Mono.fromCallable(() -> new AccessToken(encodedCredential, OffsetDateTime.MAX)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/credential/SimpleTokenCache.java b/sdk/core/azure-core/src/main/java/com/azure/core/credential/SimpleTokenCache.java index 0a8fca9d5826d..4fb3c54ffe5a9 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/credential/SimpleTokenCache.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/credential/SimpleTokenCache.java @@ -21,12 +21,13 @@ public class SimpleTokenCache { private static final Duration REFRESH_DELAY = Duration.ofSeconds(30); // the offset before token expiry to attempt proactive token refresh private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); + // SimpleTokenCache is commonly used, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(SimpleTokenCache.class); private final AtomicReference> wip; private volatile AccessToken cache; private volatile OffsetDateTime nextTokenRefresh = OffsetDateTime.now(); private final Supplier> tokenSupplier; private final Predicate shouldRefresh; - private final ClientLogger logger = new ClientLogger(SimpleTokenCache.class); /** * Creates an instance of RefreshableTokenCredential with default scheme "Bearer". @@ -86,13 +87,13 @@ public Mono getToken() { AccessToken accessToken = signal.get(); Throwable error = signal.getThrowable(); if (signal.isOnNext() && accessToken != null) { // SUCCESS - logger.info(refreshLog(cache, now, "Acquired a new access token")); + LOGGER.info(refreshLog(cache, now, "Acquired a new access token")); cache = accessToken; sinksOne.tryEmitValue(accessToken); nextTokenRefresh = OffsetDateTime.now().plus(REFRESH_DELAY); return Mono.just(accessToken); } else if (signal.isOnError() && error != null) { // ERROR - logger.error(refreshLog(cache, now, "Failed to acquire a new access token")); + LOGGER.error(refreshLog(cache, now, "Failed to acquire a new access token")); nextTokenRefresh = OffsetDateTime.now().plus(REFRESH_DELAY); return fallback.switchIfEmpty(Mono.defer(() -> Mono.error(error))); } else { // NO REFRESH diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpAuthorization.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpAuthorization.java index 475d05408a662..9e76924b2a188 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpAuthorization.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpAuthorization.java @@ -13,6 +13,9 @@ */ @Immutable public final class HttpAuthorization { + // HttpAuthorization can be used commonly, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpAuthorization.class); + private final String scheme; private final String parameter; @@ -28,12 +31,11 @@ public HttpAuthorization(String scheme, String parameter) { Objects.requireNonNull(scheme, "'scheme' cannot be null."); Objects.requireNonNull(parameter, "'parameter' cannot be null."); - ClientLogger logger = new ClientLogger(HttpAuthorization.class); if (scheme.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'scheme' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'scheme' cannot be empty.")); } if (parameter.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'parameter' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'parameter' cannot be empty.")); } this.scheme = scheme; this.parameter = parameter; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRange.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRange.java index 5f9743d8a40f2..ec9cf84015487 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRange.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRange.java @@ -18,6 +18,9 @@ */ @Immutable public final class HttpRange { + // HttpRange can be a highly used, short-lived class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpRange.class); + private final long offset; private final Long length; @@ -43,12 +46,11 @@ public HttpRange(long offset) { */ public HttpRange(long offset, Long length) { if (offset < 0) { - throw new ClientLogger(HttpRange.class).logExceptionAsError( - new IllegalArgumentException("'offset' cannot be less than 0.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'offset' cannot be less than 0.")); } if (length != null && length <= 0) { - throw new ClientLogger(HttpRange.class).logExceptionAsError( + throw LOGGER.logExceptionAsError( new IllegalArgumentException("'length' cannot be equal to or less than 0.")); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java index 4e78b3e06d6d4..3d0ae1d49e68e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/HttpRequest.java @@ -16,7 +16,8 @@ * {@link HttpHeader} and request body. */ public class HttpRequest { - private final ClientLogger logger = new ClientLogger(HttpRequest.class); + // HttpRequest is a highly used, short-lived class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpRequest.class); private HttpMethod httpMethod; private URL url; @@ -42,11 +43,7 @@ public HttpRequest(HttpMethod httpMethod, URL url) { */ public HttpRequest(HttpMethod httpMethod, String url) { this.httpMethod = httpMethod; - try { - this.url = new URL(url); - } catch (MalformedURLException ex) { - throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL", ex)); - } + setUrl(url); this.headers = new HttpHeaders(); } @@ -116,7 +113,7 @@ public HttpRequest setUrl(String url) { try { this.url = new URL(url); } catch (MalformedURLException ex) { - throw logger.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException("'url' must be a valid URL.", ex)); } return this; } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AzureKeyCredentialPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AzureKeyCredentialPolicy.java index 7ad5079eda9fe..b9c975b660b8a 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AzureKeyCredentialPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AzureKeyCredentialPolicy.java @@ -19,7 +19,8 @@ * an exception will be thrown to prevent leaking the key. */ public final class AzureKeyCredentialPolicy implements HttpPipelinePolicy { - private final ClientLogger logger = new ClientLogger(AzureKeyCredentialPolicy.class); + // AzureKeyCredentailPolicy can be a commonly used policy, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AzureKeyCredentialPolicy.class); private final String name; private final AzureKeyCredential credential; @@ -36,7 +37,7 @@ public AzureKeyCredentialPolicy(String name, AzureKeyCredential credential) { Objects.requireNonNull(credential, "'credential' cannot be null."); Objects.requireNonNull(name, "'name' cannot be null."); if (name.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'name' cannot be empty.")); } this.name = name; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java index aa8473c1b8b66..153088b608521 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/CookiePolicy.java @@ -25,7 +25,7 @@ * The pipeline policy that which stores cookies based on the response "Set-Cookie" header and adds cookies to requests. */ public class CookiePolicy implements HttpPipelinePolicy { - private final ClientLogger logger = new ClientLogger(CookiePolicy.class); + private static final ClientLogger LOGGER = new ClientLogger(CookiePolicy.class); private final CookieHandler cookies = new CookieManager(); @Override @@ -53,7 +53,7 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN try { cookies.put(uri, responseHeaders); } catch (IOException e) { - throw logger.logExceptionAsError(Exceptions.propagate(e)); + throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } return httpResponse; }); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/DefaultRedirectStrategy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/DefaultRedirectStrategy.java index d2e44f197ddb5..3df59ec8e4fed 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/DefaultRedirectStrategy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/DefaultRedirectStrategy.java @@ -22,7 +22,7 @@ * redirect status response codes (301, 302, 307, 308) to determine if request should be redirected. */ public final class DefaultRedirectStrategy implements RedirectStrategy { - private final ClientLogger logger = new ClientLogger(DefaultRedirectStrategy.class); + private static final ClientLogger LOGGER = new ClientLogger(DefaultRedirectStrategy.class); private static final int DEFAULT_MAX_REDIRECT_ATTEMPTS = 3; private static final String DEFAULT_REDIRECT_LOCATION_HEADER_NAME = "Location"; @@ -66,18 +66,18 @@ public DefaultRedirectStrategy(int maxAttempts) { */ public DefaultRedirectStrategy(int maxAttempts, String locationHeader, Set allowedMethods) { if (maxAttempts < 0) { - throw logger.logExceptionAsError(new IllegalArgumentException("Max attempts cannot be less than 0.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("Max attempts cannot be less than 0.")); } this.maxAttempts = maxAttempts; if (CoreUtils.isNullOrEmpty(locationHeader)) { - logger.error("'locationHeader' provided as null will be defaulted to {}", + LOGGER.error("'locationHeader' provided as null will be defaulted to {}", DEFAULT_REDIRECT_LOCATION_HEADER_NAME); this.locationHeader = DEFAULT_REDIRECT_LOCATION_HEADER_NAME; } else { this.locationHeader = locationHeader; } if (CoreUtils.isNullOrEmpty(allowedMethods)) { - logger.error("'allowedMethods' provided as null will be defaulted to {}", DEFAULT_REDIRECT_ALLOWED_METHODS); + LOGGER.error("'allowedMethods' provided as null will be defaulted to {}", DEFAULT_REDIRECT_ALLOWED_METHODS); this.allowedRedirectHttpMethods = DEFAULT_REDIRECT_ALLOWED_METHODS; } else { this.allowedRedirectHttpMethods = allowedMethods; @@ -94,7 +94,7 @@ && isValidRedirectCount(tryCount) && isAllowedRedirectMethod(httpResponse.getRequest().getHttpMethod())) { String redirectUrl = tryGetRedirectHeader(httpResponse.getHeaders(), getLocationHeader()); if (redirectUrl != null && !alreadyAttemptedRedirectUrl(redirectUrl, attemptedRedirectUrls)) { - logger.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", tryCount, + LOGGER.verbose("[Redirecting] Try count: {}, Attempted Redirect URLs: {}", tryCount, attemptedRedirectUrls.toString()); attemptedRedirectUrls.add(redirectUrl); return true; @@ -146,7 +146,7 @@ Set getAllowedRedirectHttpMethods() { private boolean alreadyAttemptedRedirectUrl(String redirectUrl, Set attemptedRedirectUrls) { if (attemptedRedirectUrls.contains(redirectUrl)) { - logger.error("Request was redirected more than once to: {}", redirectUrl); + LOGGER.error("Request was redirected more than once to: {}", redirectUrl); return true; } return false; @@ -160,7 +160,7 @@ private boolean alreadyAttemptedRedirectUrl(String redirectUrl, */ private boolean isValidRedirectCount(int tryCount) { if (tryCount >= getMaxAttempts()) { - logger.error("Request has been redirected more than {} times.", getMaxAttempts()); + LOGGER.error("Request has been redirected more than {} times.", getMaxAttempts()); return false; } return true; @@ -176,7 +176,7 @@ private boolean isAllowedRedirectMethod(HttpMethod httpMethod) { if (getAllowedRedirectHttpMethods().contains(httpMethod)) { return true; } else { - logger.error("Request was redirected from an invalid redirect allowed method: {}", httpMethod); + LOGGER.error("Request was redirected from an invalid redirect allowed method: {}", httpMethod); return false; } } @@ -204,7 +204,7 @@ private boolean isValidRedirectStatusCode(int statusCode) { String tryGetRedirectHeader(HttpHeaders headers, String headerName) { String headerValue = headers.getValue(headerName); if (CoreUtils.isNullOrEmpty(headerValue)) { - logger.error("Redirect url was null for header name: {}, request redirect was terminated.", headerName); + LOGGER.error("Redirect url was null for header name: {}, request redirect was terminated.", headerName); return null; } else { return headerValue; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ExponentialBackoff.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ExponentialBackoff.java index b99e999b096d9..2dc096f1ac860 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ExponentialBackoff.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ExponentialBackoff.java @@ -24,6 +24,7 @@ public class ExponentialBackoff implements RetryStrategy { private static final int DEFAULT_MAX_RETRIES; private static final Duration DEFAULT_BASE_DELAY = Duration.ofMillis(800); private static final Duration DEFAULT_MAX_DELAY = Duration.ofSeconds(8); + private static final ClientLogger LOGGER = new ClientLogger(ExponentialBackoff.class); static { String envDefaultMaxRetries = Configuration.getGlobalConfiguration().get(PROPERTY_AZURE_REQUEST_RETRY_COUNT); @@ -36,8 +37,8 @@ public class ExponentialBackoff implements RetryStrategy { defaultMaxRetries = 3; } } catch (NumberFormatException ignored) { - new ClientLogger(ExponentialBackoff.class).verbose("{} was loaded but is an invalid number. " - + "Using 3 retries as the maximum.", PROPERTY_AZURE_REQUEST_RETRY_COUNT); + LOGGER.verbose("{} was loaded but is an invalid number. Using 3 retries as the maximum.", + PROPERTY_AZURE_REQUEST_RETRY_COUNT); } } @@ -88,19 +89,18 @@ public ExponentialBackoff(ExponentialBackoffOptions options) { * to 0 or {@code maxDelay} is less than {@code baseDelay}. */ public ExponentialBackoff(int maxRetries, Duration baseDelay, Duration maxDelay) { - ClientLogger logger = new ClientLogger(ExponentialBackoff.class); if (maxRetries < 0) { - throw logger.logExceptionAsError(new IllegalArgumentException("Max retries cannot be less than 0.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("Max retries cannot be less than 0.")); } Objects.requireNonNull(baseDelay, "'baseDelay' cannot be null."); Objects.requireNonNull(maxDelay, "'maxDelay' cannot be null."); if (baseDelay.isZero() || baseDelay.isNegative()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'baseDelay' cannot be negative or 0.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'baseDelay' cannot be negative or 0.")); } if (baseDelay.compareTo(maxDelay) > 0) { - throw logger + throw LOGGER .logExceptionAsError(new IllegalArgumentException("'baseDelay' cannot be greater than 'maxDelay'.")); } this.maxRetries = maxRetries; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/FixedDelay.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/FixedDelay.java index 9a3ad1159de3e..880d700f25591 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/FixedDelay.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/FixedDelay.java @@ -11,6 +11,8 @@ * A fixed-delay implementation of {@link RetryStrategy} that has a fixed delay duration between each retry attempt. */ public class FixedDelay implements RetryStrategy { + private static final ClientLogger LOGGER = new ClientLogger(FixedDelay.class); + private final int maxRetries; private final Duration delay; @@ -24,8 +26,7 @@ public class FixedDelay implements RetryStrategy { */ public FixedDelay(int maxRetries, Duration delay) { if (maxRetries < 0) { - ClientLogger logger = new ClientLogger(FixedDelay.class); - throw logger.logExceptionAsError(new IllegalArgumentException("Max retries cannot be less than 0.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("Max retries cannot be less than 0.")); } this.maxRetries = maxRetries; this.delay = Objects.requireNonNull(delay, "'delay' cannot be null."); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java index ed08ee6d81f2e..223b6f4db1116 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HostPolicy.java @@ -18,8 +18,9 @@ * The pipeline policy that adds the given host to each HttpRequest. */ public class HostPolicy implements HttpPipelinePolicy { + private static final ClientLogger LOGGER = new ClientLogger(HostPolicy.class); + private final String host; - private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. @@ -32,7 +33,7 @@ public HostPolicy(String host) { @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { - logger.log(LogLevel.VERBOSE, () -> "Setting host to " + host); + LOGGER.log(LogLevel.VERBOSE, () -> "Setting host to " + host); final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogOptions.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogOptions.java index 79ac4ba589429..f049b5c66e7b6 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogOptions.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLogOptions.java @@ -27,7 +27,8 @@ public class HttpLogOptions { private HttpRequestLogger requestLogger; private HttpResponseLogger responseLogger; - private final ClientLogger logger = new ClientLogger(HttpLogOptions.class); + // HttpLogOptions is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpLogOptions.class); private static final int MAX_APPLICATION_ID_LENGTH = 24; private static final String INVALID_APPLICATION_ID_LENGTH = "'applicationId' length cannot be greater than " @@ -197,9 +198,9 @@ public String getApplicationId() { public HttpLogOptions setApplicationId(final String applicationId) { if (!CoreUtils.isNullOrEmpty(applicationId)) { if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { - throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_LENGTH)); + throw LOGGER.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_LENGTH)); } else if (applicationId.contains(" ")) { - throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE)); + throw LOGGER.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java index 6a1f9c9812060..d772dfdff5d30 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java @@ -29,7 +29,9 @@ import java.time.Duration; import java.util.Collections; import java.util.Locale; +import java.util.Map; import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; /** @@ -40,7 +42,16 @@ public class HttpLoggingPolicy implements HttpPipelinePolicy { private static final int MAX_BODY_LOG_SIZE = 1024 * 16; private static final String REDACTED_PLACEHOLDER = "REDACTED"; - private final ClientLogger logger = new ClientLogger(HttpLoggingPolicy.class); + // Use a cache to retain the caller method ClientLogger. + // + // The same method may be called thousands or millions of times, so it is wasteful to create a new logger instance + // each time the method is called. Instead, retain the created ClientLogger until a certain number of unique method + // calls have been made and then clear the cache and rebuild it. Long term, this should be replaced with an LRU, + // or another type of cache, for better cache management. + private static final int LOGGER_CACHE_MAX_SIZE = 1000; + private static final Map CALLER_METHOD_LOGGER_CACHE = new ConcurrentHashMap<>(); + + private static final ClientLogger LOGGER = new ClientLogger(HttpLoggingPolicy.class); private final HttpLogDetailLevel httpLogDetailLevel; private final Set allowedHeaderNames; @@ -97,7 +108,8 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN return next.process(); } - final ClientLogger logger = new ClientLogger((String) context.getData("caller-method").orElse("")); + + final ClientLogger logger = getOrCreateMethodLogger((String) context.getData("caller-method").orElse("")); final long startNs = System.nanoTime(); return requestLogger.logRequest(logger, getRequestLoggingOptions(context)) @@ -110,14 +122,14 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN private HttpRequestLoggingContext getRequestLoggingOptions(HttpPipelineCallContext callContext) { return new HttpRequestLoggingContext(callContext.getHttpRequest(), HttpPipelineCallContextHelper.getContext(callContext), - getRequestRetryCount(HttpPipelineCallContextHelper.getContext(callContext), getHttpLoggingPolicyLogger())); + getRequestRetryCount(HttpPipelineCallContextHelper.getContext(callContext), LOGGER)); } private HttpResponseLoggingContext getResponseLoggingOptions(HttpResponse httpResponse, long startNs, HttpPipelineCallContext callContext) { return new HttpResponseLoggingContext(httpResponse, Duration.ofNanos(System.nanoTime() - startNs), HttpPipelineCallContextHelper.getContext(callContext), - getRequestRetryCount(HttpPipelineCallContextHelper.getContext(callContext), getHttpLoggingPolicyLogger())); + getRequestRetryCount(HttpPipelineCallContextHelper.getContext(callContext), LOGGER)); } private final class DefaultHttpRequestLogger implements HttpRequestLogger { @@ -271,10 +283,6 @@ public Mono logResponse(ClientLogger logger, HttpResponseLoggingCo } } - private ClientLogger getHttpLoggingPolicyLogger() { - return this.logger; - } - private static Mono logAndReturn(ClientLogger logger, LogLevel logLevel, StringBuilder logMessageBuilder, T data) { switch (logLevel) { @@ -484,4 +492,15 @@ private static Integer getRequestRetryCount(Context context, ClientLogger logger return null; } } + + /* + * Get or create the ClientLogger for the method having its request and response logged. + */ + private static ClientLogger getOrCreateMethodLogger(String methodName) { + if (CALLER_METHOD_LOGGER_CACHE.size() > LOGGER_CACHE_MAX_SIZE) { + CALLER_METHOD_LOGGER_CACHE.clear(); + } + + return CALLER_METHOD_LOGGER_CACHE.computeIfAbsent(methodName, ClientLogger::new); + } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java index 48cacdf6e4ae4..30387aa9208a0 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/PortPolicy.java @@ -18,9 +18,10 @@ * The pipeline policy that adds a given port to each {@link HttpRequest}. */ public class PortPolicy implements HttpPipelinePolicy { + private static final ClientLogger LOGGER = new ClientLogger(PortPolicy.class); + private final int port; private final boolean overwrite; - private final ClientLogger logger = new ClientLogger(PortPolicy.class); /** * Creates a new PortPolicy object. @@ -37,7 +38,7 @@ public PortPolicy(int port, boolean overwrite) { public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); if (overwrite || urlBuilder.getPort() == null) { - logger.log(LogLevel.VERBOSE, () -> "Changing port to " + port); + LOGGER.log(LogLevel.VERBOSE, () -> "Changing port to " + port); try { context.getHttpRequest().setUrl(urlBuilder.setPort(port).toUrl()); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java index 2b0dc22cce45a..3bbf9791f249f 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/ProtocolPolicy.java @@ -17,9 +17,10 @@ * The pipeline policy that adds a given protocol to each HttpRequest. */ public class ProtocolPolicy implements HttpPipelinePolicy { + private static final ClientLogger LOGGER = new ClientLogger(ProtocolPolicy.class); + private final String protocol; private final boolean overwrite; - private final ClientLogger logger = new ClientLogger(ProtocolPolicy.class); /** * Creates a new ProtocolPolicy. @@ -36,7 +37,7 @@ public ProtocolPolicy(String protocol, boolean overwrite) { public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); if (overwrite || urlBuilder.getScheme() == null) { - logger.log(LogLevel.VERBOSE, () -> "Setting protocol to " + protocol); + LOGGER.log(LogLevel.VERBOSE, () -> "Setting protocol to " + protocol); try { context.getHttpRequest().setUrl(urlBuilder.setScheme(protocol).toUrl()); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java index ae47b050df6e4..52aac54b7d566 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/RetryPolicy.java @@ -26,7 +26,8 @@ * A pipeline policy that retries when a recoverable HTTP error or exception occurs. */ public class RetryPolicy implements HttpPipelinePolicy { - private final ClientLogger logger = new ClientLogger(RetryPolicy.class); + // RetryPolicy is a commonly used policy, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(RetryPolicy.class); private final RetryStrategy retryStrategy; private final String retryAfterHeader; @@ -126,7 +127,7 @@ private Mono attemptAsync(final HttpPipelineCallContext context, f if (shouldRetry(httpResponse, tryCount)) { final Duration delayDuration = determineDelayDuration(httpResponse, tryCount, retryStrategy, retryAfterHeader, retryAfterTimeUnit); - logger.verbose("[Retrying] Try count: {}, Delay duration in seconds: {}", tryCount, + LOGGER.verbose("[Retrying] Try count: {}, Delay duration in seconds: {}", tryCount, delayDuration.getSeconds()); Flux responseBody = httpResponse.getBody(); @@ -141,18 +142,18 @@ private Mono attemptAsync(final HttpPipelineCallContext context, f } } else { if (tryCount >= retryStrategy.getMaxRetries()) { - logger.info("Retry attempts have been exhausted after {} attempts.", tryCount); + LOGGER.info("Retry attempts have been exhausted after {} attempts.", tryCount); } return Mono.just(httpResponse); } }) .onErrorResume(err -> { if (shouldRetryException(err, tryCount)) { - logger.verbose("[Error Resume] Try count: {}, Error: {}", tryCount, err); + LOGGER.verbose("[Error Resume] Try count: {}, Error: {}", tryCount, err); return attemptAsync(context, next, originalHttpRequest, tryCount + 1) .delaySubscription(retryStrategy.calculateRetryDelay(tryCount)); } else { - logger.info("Retry attempts have been exhausted after {} attempts.", tryCount, err); + LOGGER.info("Retry attempts have been exhausted after {} attempts.", tryCount, err); return Mono.error(err); } }); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PercentEscaper.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PercentEscaper.java index 7e710c1a5cc04..6f5e61450a88f 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PercentEscaper.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/PercentEscaper.java @@ -20,7 +20,7 @@ final class PercentEscaper { */ private static final String SAFE_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - private final ClientLogger logger = new ClientLogger(PercentEscaper.class); + private static final ClientLogger LOGGER = new ClientLogger(PercentEscaper.class); private final boolean usePlusForSpace; private final Set safeCharacterPoints; @@ -35,7 +35,7 @@ final class PercentEscaper { this.usePlusForSpace = usePlusForSpace; if (usePlusForSpace && safeCharacters != null && safeCharacters.contains(" ")) { - throw logger.logExceptionAsError(new IllegalArgumentException( + throw LOGGER.logExceptionAsError(new IllegalArgumentException( "' ' as a safe character with 'usePlusForSpace = true' is an invalid configuration.")); } @@ -68,7 +68,7 @@ public String escape(String original) { * the conversion. */ while (index < end) { - int codePoint = getCodePoint(original, index, end, logger); + int codePoint = getCodePoint(original, index, end); // Supplementary code points are comprised of two characters in the string. index += (Character.isSupplementaryCodePoint(codePoint)) ? 2 : 1; @@ -212,7 +212,7 @@ public String escape(String original) { * Java uses UTF-16 to represent Strings, due to characters only being 2 bytes they must use surrogate pairs to * get the correct code point for characters above 0xFFFF. */ - private static int getCodePoint(String original, int index, int end, ClientLogger logger) { + private static int getCodePoint(String original, int index, int end) { char char1 = original.charAt(index++); if (!Character.isSurrogate(char1)) { // Character isn't a surrogate, return it as is. @@ -220,7 +220,7 @@ private static int getCodePoint(String original, int index, int end, ClientLogge } else if (Character.isHighSurrogate(char1)) { // High surrogates will occur first in the string. if (index == end) { - throw logger.logExceptionAsError(new IllegalStateException( + throw LOGGER.logExceptionAsError(new IllegalStateException( "String contains trailing high surrogate without paired low surrogate.")); } @@ -229,10 +229,10 @@ private static int getCodePoint(String original, int index, int end, ClientLogge return Character.toCodePoint(char1, char2); } - throw logger.logExceptionAsError(new IllegalStateException( + throw LOGGER.logExceptionAsError(new IllegalStateException( "String contains high surrogate without trailing low surrogate.")); } else { - throw logger.logExceptionAsError(new IllegalStateException( + throw LOGGER.logExceptionAsError(new IllegalStateException( "String contains low surrogate without leading high surrogate.")); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseConstructorsCache.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseConstructorsCache.java index 8f8b3c1dd9f1b..3fdbe99720e99 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseConstructorsCache.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/ResponseConstructorsCache.java @@ -32,7 +32,7 @@ final class ResponseConstructorsCache { private static final Map, MethodHandle> CACHE = new ConcurrentHashMap<>(); - private final ClientLogger logger = new ClientLogger(ResponseConstructorsCache.class); + private static final ClientLogger LOGGER = new ClientLogger(ResponseConstructorsCache.class); /** * Identify the suitable {@link MethodHandle} to construct the given response class. @@ -68,7 +68,7 @@ private MethodHandle locateResponseConstructor(Class responseClass) { try { lookupToUse = ReflectionUtilsApi.INSTANCE.getLookupToUse(responseClass); } catch (Throwable t) { - throw logger.logExceptionAsError(new RuntimeException(t)); + throw LOGGER.logExceptionAsError(new RuntimeException(t)); } /* @@ -94,7 +94,7 @@ private MethodHandle locateResponseConstructor(Class responseClass) { */ return lookupToUse.unreflectConstructor(constructor); } catch (Throwable t) { - throw logger.logExceptionAsError(new RuntimeException(t)); + throw LOGGER.logExceptionAsError(new RuntimeException(t)); } } } @@ -119,16 +119,16 @@ Mono> invoke(final MethodHandle handle, final int paramCount = handle.type().parameterCount(); switch (paramCount) { case 3: - return constructResponse(handle, THREE_PARAM_ERROR, logger, httpRequest, responseStatusCode, + return constructResponse(handle, THREE_PARAM_ERROR, LOGGER, httpRequest, responseStatusCode, responseHeaders); case 4: - return constructResponse(handle, FOUR_PARAM_ERROR, logger, httpRequest, responseStatusCode, + return constructResponse(handle, FOUR_PARAM_ERROR, LOGGER, httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: - return constructResponse(handle, FIVE_PARAM_ERROR, logger, httpRequest, responseStatusCode, + return constructResponse(handle, FIVE_PARAM_ERROR, LOGGER, httpRequest, responseStatusCode, responseHeaders, bodyAsObject, decodedResponse.getDecodedHeaders()); default: - return monoError(logger, new IllegalStateException(INVALID_PARAM_COUNT)); + return monoError(LOGGER, new IllegalStateException(INVALID_PARAM_COUNT)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java index eee245d5f4e41..aebd5f05adb9c 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/rest/RestProxy.java @@ -72,7 +72,9 @@ public final class RestProxy implements InvocationHandler { private static final ResponseConstructorsCache RESPONSE_CONSTRUCTORS_CACHE = new ResponseConstructorsCache(); - private final ClientLogger logger = new ClientLogger(RestProxy.class); + // RestProxy is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(RestProxy.class); + private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; @@ -148,7 +150,7 @@ public Object invoke(Object proxy, final Method method, Object[] args) { return handleRestReturnType(asyncDecodedResponse, methodParser, methodParser.getReturnType(), context, options); } catch (IOException e) { - throw logger.logExceptionAsError(Exceptions.propagate(e)); + throw LOGGER.logExceptionAsError(Exceptions.propagate(e)); } } @@ -157,7 +159,7 @@ void validateResumeOperationIsNotPresent(Method method) { // Use the fully-qualified class name as javac will throw deprecation warnings on imports when the class is // marked as deprecated. if (method.isAnnotationPresent(com.azure.core.annotation.ResumeOperation.class)) { - throw logger.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); + throw LOGGER.logExceptionAsError(Exceptions.propagate(new Exception("'ResumeOperation' isn't supported."))); } } @@ -479,7 +481,7 @@ private Mono> createResponse(HttpDecodedResponse response, Type enti cls = (Class>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { - return monoError(logger, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); + return monoError(LOGGER, new RuntimeException(MUST_IMPLEMENT_PAGE_ERROR)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/AccessTokenCache.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/AccessTokenCache.java index 94370b700aa94..a50147e4c0faa 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/AccessTokenCache.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/AccessTokenCache.java @@ -28,6 +28,8 @@ public final class AccessTokenCache { private static final Duration REFRESH_DELAY = Duration.ofSeconds(30); // the offset before token expiry to attempt proactive token refresh private static final Duration REFRESH_OFFSET = Duration.ofMinutes(5); + // AccessTokenCache is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AccessTokenCache.class); private final AtomicReference> wip; private volatile AccessToken cache; private volatile OffsetDateTime nextTokenRefresh = OffsetDateTime.now(); @@ -35,7 +37,6 @@ public final class AccessTokenCache { // Stores the last authenticated token request context. The cached token is valid under this context. private TokenRequestContext tokenRequestContext; private final Predicate shouldRefresh; - private final ClientLogger logger = new ClientLogger(AccessTokenCache.class); /** * Creates an instance of RefreshableTokenCredential with default scheme "Bearer". @@ -66,7 +67,7 @@ private Supplier> retrieveToken(TokenRequestContext return () -> { try { if (tokenRequestContext == null) { - return Mono.error(logger.logExceptionAsError( + return Mono.error(LOGGER.logExceptionAsError( new IllegalArgumentException("The token request context input cannot be null."))); } if (wip.compareAndSet(null, Sinks.one())) { @@ -159,13 +160,13 @@ private Function, Mono> processTokenR AccessToken accessToken = signal.get(); Throwable error = signal.getThrowable(); if (signal.isOnNext() && accessToken != null) { // SUCCESS - logger.info(refreshLog(cache, now, "Acquired a new access token")); + LOGGER.info(refreshLog(cache, now, "Acquired a new access token")); cache = accessToken; sinksOne.tryEmitValue(accessToken); nextTokenRefresh = OffsetDateTime.now().plus(REFRESH_DELAY); return Mono.just(accessToken); } else if (signal.isOnError() && error != null) { // ERROR - logger.error(refreshLog(cache, now, "Failed to acquire a new access token")); + LOGGER.error(refreshLog(cache, now, "Failed to acquire a new access token")); nextTokenRefresh = OffsetDateTime.now().plus(REFRESH_DELAY); return fallback.switchIfEmpty(Mono.defer(() -> Mono.error(error))); } else { // NO REFRESH diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ByteBufferCollector.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ByteBufferCollector.java index 1fbdfe6d3a022..cc62e028cddd8 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ByteBufferCollector.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/ByteBufferCollector.java @@ -25,7 +25,8 @@ public final class ByteBufferCollector { private static final String INVALID_INITIAL_SIZE = "'initialSize' cannot be less than 0."; private static final String REQUESTED_BUFFER_INVALID = "Required capacity is greater than Integer.MAX_VALUE."; - private final ClientLogger logger = new ClientLogger(ByteBufferCollector.class); + // ByteBufferCollector is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(ByteBufferCollector.class); private byte[] buffer; private int position; @@ -45,7 +46,7 @@ public ByteBufferCollector() { */ public ByteBufferCollector(int initialSize) { if (initialSize < 0) { - throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_INITIAL_SIZE)); + throw LOGGER.logExceptionAsError(new IllegalArgumentException(INVALID_INITIAL_SIZE)); } this.buffer = new byte[initialSize]; @@ -98,7 +99,7 @@ private void ensureCapacity(int byteBufferRemaining) throws OutOfMemoryError { * overflow response by checking that the result uses the same sign as both of the addition arguments. */ if (((position ^ requiredCapacity) & (byteBufferRemaining ^ requiredCapacity)) < 0) { - throw logger.logExceptionAsError(new IllegalStateException(REQUESTED_BUFFER_INVALID)); + throw LOGGER.logExceptionAsError(new IllegalStateException(REQUESTED_BUFFER_INVALID)); } // Buffer is already large enough to accept the data being written. diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/FileWriteSubscriber.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/FileWriteSubscriber.java index f64122c3f6ff6..6bac551e23f5b 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/FileWriteSubscriber.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/FileWriteSubscriber.java @@ -26,7 +26,8 @@ public final class FileWriteSubscriber implements Subscriber { private volatile boolean isWriting = false; private volatile boolean isCompleted = false; - private final ClientLogger logger = new ClientLogger(FileWriteSubscriber.class); + // FileWriteSubscriber is a commonly used subscriber, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(FileWriteSubscriber.class); private final AsynchronousFileChannel fileChannel; private final AtomicLong position; @@ -98,7 +99,7 @@ public void failed(Throwable exc, ByteBuffer attachment) { public void onError(Throwable throwable) { isWriting = false; subscription.cancel(); - emitter.error(logger.logThrowableAsError(throwable)); + emitter.error(LOGGER.logThrowableAsError(throwable)); } @Override diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java index 3ca3b449a6e41..bc3831cebd9c8 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/http/BufferedHttpResponse.java @@ -22,7 +22,8 @@ * HTTP response which will buffer the response's body when/if it is read. */ public final class BufferedHttpResponse extends HttpResponse { - private final ClientLogger logger = new ClientLogger(BufferedHttpResponse.class); + // BufferedHttpResponse is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(BufferedHttpResponse.class); private final HttpResponse innerHttpResponse; private final Mono> cachedBody; @@ -69,7 +70,7 @@ public Flux getBody() { public Mono getBodyAsByteArray() { // Check that the body would fit into a byte array before spending time to create the merged byte array. return (cachedBodySize.get() > Integer.MAX_VALUE) - ? monoError(logger, new IllegalStateException( + ? monoError(LOGGER, new IllegalStateException( "Response with body size " + cachedBodySize.get() + " doesn't fit into a byte array.")) : FluxUtil.collectBytesInByteBufferStream(getBody(), (int) cachedBodySize.get()); } @@ -78,7 +79,7 @@ public Mono getBodyAsByteArray() { public Mono getBodyAsString() { // Check that the body would fit into a String before spending the time to create the String. return (cachedBodySize.get() > Integer.MAX_VALUE) - ? monoError(logger, new IllegalStateException( + ? monoError(LOGGER, new IllegalStateException( "Response with body size " + cachedBodySize.get() + " doesn't fit into a String.")) : getBodyAsByteArray().map(bytes -> CoreUtils.bomAwareToString(bytes, innerHttpResponse.getHeaderValue("Content-Type"))); @@ -88,7 +89,7 @@ public Mono getBodyAsString() { public Mono getBodyAsString(Charset charset) { // Check that the body would fit into a String before spending the time to create the String. return (cachedBodySize.get() > Integer.MAX_VALUE) - ? monoError(logger, new IllegalStateException( + ? monoError(LOGGER, new IllegalStateException( "Response with body size " + cachedBodySize.get() + " doesn't fit into a String.")) : getBodyAsByteArray().map(bytes -> new String(bytes, charset)); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/FlatteningSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/FlatteningSerializer.java index 1a667902da729..8ec5da192ac7e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/FlatteningSerializer.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/FlatteningSerializer.java @@ -62,7 +62,8 @@ class FlatteningSerializer extends StdSerializer implements ResolvableSe private static final Pattern CHECK_IF_ESCAPED_MAP_PATTERN = Pattern.compile(".*[^\\\\]\\\\..+"); private static final Pattern REPLACE_ESCAPED_MAP_PATTERN = Pattern.compile("\\\\."); - private final ClientLogger logger = new ClientLogger(FlatteningSerializer.class); + // FlatteningSerializer is a commonly used serializer, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(FlatteningSerializer.class); private final BeanDescription beanDescription; @@ -309,7 +310,7 @@ private void propertyOnlyFlattenSerialize(Object value, JsonGenerator gen, Seria try { anyGetterWriter.getAndSerialize(value, gen, provider); } catch (Exception exception) { - throw logger.logThrowableAsError(new IOException(exception)); + throw LOGGER.logThrowableAsError(new IOException(exception)); } } @@ -317,7 +318,7 @@ private void propertyOnlyFlattenSerialize(Object value, JsonGenerator gen, Seria } private void classLevelFlattenSerialize(Object value, JsonGenerator gen) throws IOException { - escapeMapKeys(value, logger); + escapeMapKeys(value, LOGGER); // BFS for all collapsed properties ObjectNode root = mapper.valueToTree(value); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/JacksonVersion.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/JacksonVersion.java index caa334670c5af..4893cecc3c006 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/JacksonVersion.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/JacksonVersion.java @@ -34,10 +34,11 @@ final class JacksonVersion { .getProperties(AZURE_CORE_PROPERTIES_NAME) .getOrDefault(AZURE_CORE_PROPERTIES_VERSION_KEY, SemanticVersion.UNKNOWN_VERSION); + private static final ClientLogger LOGGER = new ClientLogger(JacksonVersion.class); + private static JacksonVersion instance = null; private final String helpString; - private final ClientLogger logger = new ClientLogger(JacksonVersion.class); private JacksonVersion() { annotationsVersion = SemanticVersion.getPackageVersionForClass("com.fasterxml.jackson.annotation.JsonProperty"); @@ -51,7 +52,7 @@ private JacksonVersion() { checkVersion(xmlVersion, XML_PACKAGE_NAME); checkVersion(jsr310Version, JSR310_PACKAGE_NAME); helpString = formatHelpString(); - logger.info(helpString); + LOGGER.info(helpString); } /** @@ -79,16 +80,16 @@ public static synchronized JacksonVersion getInstance() { */ private void checkVersion(SemanticVersion version, String packageName) { if (!version.isValid()) { - logger.verbose("Could not find version of '{}'.", packageName); + LOGGER.verbose("Could not find version of '{}'.", packageName); return; } if (version.compareTo(MIN_SUPPORTED_VERSION) < 0) { - logger.error("Version '{}' of package '{}' is not supported (older than earliest supported version - `{}`), please upgrade.", version.getVersionString(), packageName, MIN_SUPPORTED_VERSION); + LOGGER.error("Version '{}' of package '{}' is not supported (older than earliest supported version - `{}`), please upgrade.", version.getVersionString(), packageName, MIN_SUPPORTED_VERSION); } if (version.getMajorVersion() > MAX_SUPPORTED_MAJOR_VERSION) { - logger.error("Major version '{}' of package '{}' is newer than latest supported version - '{}'.", + LOGGER.error("Major version '{}' of package '{}' is newer than latest supported version - '{}'.", version.getVersionString(), packageName, MAX_SUPPORTED_MAJOR_VERSION); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/ObjectMapperFactory.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/ObjectMapperFactory.java index 2ce8a2d8b54ad..50aae24cf9f0a 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/ObjectMapperFactory.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/jackson/ObjectMapperFactory.java @@ -26,7 +26,8 @@ * Constructs and configures {@link ObjectMapper} instances. */ final class ObjectMapperFactory { - private final ClientLogger logger = new ClientLogger(ObjectMapperFactory.class); + // ObjectMapperFactory is a commonly used factory, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(ObjectMapperFactory.class); private static final String MUTABLE_COERCION_CONFIG = "com.fasterxml.jackson.databind.cfg.MutableCoercionConfig"; private static final String COERCION_INPUT_SHAPE = "com.fasterxml.jackson.databind.cfg.CoercionInputShape"; @@ -60,7 +61,7 @@ private ObjectMapperFactory() { .invoke(); useReflectionToSetCoercion = true; } catch (Throwable ex) { - logger.verbose("Failed to retrieve MethodHandles used to set coercion configurations. " + LOGGER.verbose("Failed to retrieve MethodHandles used to set coercion configurations. " + "Setting coercion configurations will be skipped.", ex); } } @@ -96,10 +97,10 @@ public ObjectMapper createXmlMapper() { Object object = coersionConfigDefaults.invoke(xmlMapper); setCoercion.invoke(object, coercionInputShapeEmptyString, coercionActionAsNull); } catch (Throwable e) { - logger.verbose("Failed to set coercion actions.", e); + LOGGER.verbose("Failed to set coercion actions.", e); } } else { - logger.verbose("Didn't set coercion defaults as it wasn't found on the classpath."); + LOGGER.verbose("Didn't set coercion defaults as it wasn't found on the classpath."); } return xmlMapper; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/DefaultJsonSerializer.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/DefaultJsonSerializer.java index 36cc9b085e360..41d858ce97bc3 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/DefaultJsonSerializer.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/DefaultJsonSerializer.java @@ -21,15 +21,17 @@ * no JsonSerializerProvider is in the class path. */ public final class DefaultJsonSerializer implements JsonSerializer { + // DefaultJsonSerializer is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(DefaultJsonSerializer.class); + private final SerializerAdapter jacksonAdapter = JacksonAdapter.createDefaultSerializerAdapter(); - private final ClientLogger logger = new ClientLogger(DefaultJsonSerializer.class); @Override public T deserializeFromBytes(byte[] data, TypeReference typeReference) { try { return jacksonAdapter.deserialize(data, typeReference.getJavaType(), SerializerEncoding.JSON); } catch (IOException e) { - throw logger.logExceptionAsError(new UncheckedIOException(e)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } @@ -38,7 +40,7 @@ public T deserialize(InputStream stream, TypeReference typeReference) { try { return jacksonAdapter.deserialize(stream, typeReference.getJavaType(), SerializerEncoding.JSON); } catch (IOException e) { - throw logger.logExceptionAsError(new UncheckedIOException(e)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } @@ -57,7 +59,7 @@ public byte[] serializeToBytes(Object value) { try { return jacksonAdapter.serializeToBytes(value, SerializerEncoding.JSON); } catch (IOException e) { - throw logger.logExceptionAsError(new UncheckedIOException(e)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } @@ -66,7 +68,7 @@ public void serialize(OutputStream stream, Object value) { try { jacksonAdapter.serialize(value, SerializerEncoding.JSON, stream); } catch (IOException e) { - throw logger.logExceptionAsError(new UncheckedIOException(e)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(e)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java index b8f9388649240..2bfa7b6ba8615 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/serializer/HttpResponseBodyDecoder.java @@ -44,6 +44,9 @@ public final class HttpResponseBodyDecoder { private static final Map RETURN_TYPE_DECODEABLE_MAP = new ConcurrentHashMap<>(); + // HttpResponseBodyDecoder is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(HttpResponseBodyDecoder.class); + // TODO (jogiles) JavaDoc (even though it is non-public static Mono decode(final String body, final HttpResponse httpResponse, @@ -72,7 +75,6 @@ static Mono decodeByteArray(final byte[] body, final SerializerAdapter serializer, final HttpResponseDecodeData decodeData) { ensureRequestSet(httpResponse); - final ClientLogger logger = new ClientLogger(HttpResponseBodyDecoder.class); return Mono.defer(() -> { if (isErrorStatus(httpResponse, decodeData)) { @@ -87,7 +89,7 @@ static Mono decodeByteArray(final byte[] body, } catch (IOException | MalformedValueException ex) { // This translates in RestProxy as a RestException with no deserialized body. // The response content will still be accessible via the .response() member. - logger.warning("Failed to deserialize the error entity.", ex); + LOGGER.warning("Failed to deserialize the error entity.", ex); return Mono.empty(); } }); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoArray.java b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoArray.java index f61adbd42e614..9e0b646efdc24 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoArray.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoArray.java @@ -22,7 +22,8 @@ @Immutable final class GeoArray extends AbstractList { private static final String NO_MUTATION_MESSAGE = "GeoArray cannot be mutated."; - private final ClientLogger logger = new ClientLogger(GeoArray.class); + // GeoArray is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoArray.class); private final Object container; @@ -44,7 +45,7 @@ public T get(int index) { } else if (container instanceof GeoPolygonCollection) { return (T) ((GeoPolygonCollection) container).getPolygons().get(index).getCoordinates(); } else { - throw logger.logExceptionAsError(new IllegalStateException()); + throw LOGGER.logExceptionAsError(new IllegalStateException()); } } @@ -61,7 +62,7 @@ public int size() { } else if (container instanceof GeoPolygonCollection) { return ((GeoPolygonCollection) container).getPolygons().size(); } else { - throw logger.logExceptionAsError(new IllegalStateException()); + throw LOGGER.logExceptionAsError(new IllegalStateException()); } } @@ -74,7 +75,7 @@ public int size() { */ @Override public boolean remove(Object o) { - throw logger.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); } /** @@ -86,7 +87,7 @@ public boolean remove(Object o) { */ @Override public boolean removeAll(Collection c) { - throw logger.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); } /** @@ -98,7 +99,7 @@ public boolean removeAll(Collection c) { */ @Override public boolean retainAll(Collection c) { - throw logger.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); } /** @@ -109,7 +110,7 @@ public boolean retainAll(Collection c) { */ @Override public void replaceAll(UnaryOperator operator) { - throw logger.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); } /** @@ -120,7 +121,7 @@ public void replaceAll(UnaryOperator operator) { */ @Override public void sort(Comparator c) { - throw logger.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); } /** @@ -132,7 +133,7 @@ public void sort(Comparator c) { */ @Override public boolean removeIf(Predicate filter) { - throw logger.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException(NO_MUTATION_MESSAGE)); } /** @@ -145,7 +146,7 @@ public boolean removeIf(Predicate filter) { */ @Override public List subList(int fromIndex, int toIndex) { - throw logger.logExceptionAsError(new UnsupportedOperationException("GeoArray does not support sub lists.")); + throw LOGGER.logExceptionAsError(new UnsupportedOperationException("GeoArray does not support sub lists.")); } @Override diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoBoundingBox.java b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoBoundingBox.java index 84144792c9298..a755e726da811 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoBoundingBox.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoBoundingBox.java @@ -13,7 +13,8 @@ */ @Immutable public final class GeoBoundingBox { - private final ClientLogger logger = new ClientLogger(GeoBoundingBox.class); + // GeoBoundingBox is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoBoundingBox.class); private final double west; private final double south; @@ -165,7 +166,7 @@ public boolean equals(Object obj) { case 5: return maxAltitude; default: - throw logger.logExceptionAsWarning(new IndexOutOfBoundsException("Index out of range: " + i)); + throw LOGGER.logExceptionAsWarning(new IndexOutOfBoundsException("Index out of range: " + i)); } } else { switch (i) { @@ -178,7 +179,7 @@ public boolean equals(Object obj) { case 3: return north; default: - throw logger.logExceptionAsWarning(new IndexOutOfBoundsException("Index out of range: " + i)); + throw LOGGER.logExceptionAsWarning(new IndexOutOfBoundsException("Index out of range: " + i)); } } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoLinearRing.java b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoLinearRing.java index eb960f7f23bc6..1841c90dfa750 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoLinearRing.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoLinearRing.java @@ -15,6 +15,9 @@ */ @Immutable public final class GeoLinearRing { + // GeoLinearRing is a commonly used model class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoLinearRing.class); + private final GeoArray coordinates; /** @@ -28,15 +31,14 @@ public final class GeoLinearRing { public GeoLinearRing(List coordinates) { Objects.requireNonNull(coordinates, "'coordinates' cannot be null."); - ClientLogger logger = new ClientLogger(GeoLinearRing.class); int size = coordinates.size(); if (size < 4) { - throw logger.logExceptionAsError( + throw LOGGER.logExceptionAsError( new IllegalArgumentException("A linear ring requires at least 4 coordinates.")); } if (!Objects.equals(coordinates.get(0), coordinates.get(size - 1))) { - throw logger.logExceptionAsError( + throw LOGGER.logExceptionAsError( new IllegalArgumentException("The first and last coordinates of a linear ring must be equivalent.")); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoPosition.java b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoPosition.java index 6d6c5fbdc3dd7..d8071a032cabd 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoPosition.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/models/GeoPosition.java @@ -13,7 +13,8 @@ */ @Immutable public final class GeoPosition { - private final ClientLogger logger = new ClientLogger(GeoPosition.class); + // GeoPosition is a commonly used model, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(GeoPosition.class); private final double longitude; private final double latitude; @@ -119,13 +120,13 @@ public int count() { return latitude; case 2: if (altitude == null) { - throw logger.logExceptionAsError(new IndexOutOfBoundsException("Index out of range: " + index)); + throw LOGGER.logExceptionAsError(new IndexOutOfBoundsException("Index out of range: " + index)); } return altitude; default: - throw logger.logExceptionAsError(new IndexOutOfBoundsException("Index out of range: " + index)); + throw LOGGER.logExceptionAsError(new IndexOutOfBoundsException("Index out of range: " + index)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/models/JsonPatchDocument.java b/sdk/core/azure-core/src/main/java/com/azure/core/models/JsonPatchDocument.java index 2c0d8a6dad69c..cadb4f7687409 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/models/JsonPatchDocument.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/models/JsonPatchDocument.java @@ -25,8 +25,9 @@ public final class JsonPatchDocument { private static final Object SERIALIZER_INSTANTIATION_SYNCHRONIZER = new Object(); private static volatile JsonSerializer defaultSerializer; + // JsonPatchDocument is a commonly used model, use a static logger. @JsonIgnore - private final ClientLogger logger = new ClientLogger(JsonPatchDocument.class); + private static final ClientLogger LOGGER = new ClientLogger(JsonPatchDocument.class); @JsonIgnore private final JsonSerializer serializer; @@ -478,7 +479,7 @@ private Option serializeValue(Object value) { rawValue = outputStream.toString("UTF-8"); } catch (IOException ex) { - throw logger.logExceptionAsError(new UncheckedIOException(ex)); + throw LOGGER.logExceptionAsError(new UncheckedIOException(ex)); } return Option.of(rawValue); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/ClientOptions.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/ClientOptions.java index 75902c07315a9..6d3c38ae7b0ff 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/ClientOptions.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/ClientOptions.java @@ -19,7 +19,8 @@ public class ClientOptions { + MAX_APPLICATION_ID_LENGTH; private static final String INVALID_APPLICATION_ID_SPACE = "'applicationId' cannot contain spaces."; - private final ClientLogger logger = new ClientLogger(ClientOptions.class); + // ClientOptions is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(ClientOptions.class); private Iterable
headers; private String applicationId; @@ -62,9 +63,9 @@ public String getApplicationId() { public ClientOptions setApplicationId(String applicationId) { if (!CoreUtils.isNullOrEmpty(applicationId)) { if (applicationId.length() > MAX_APPLICATION_ID_LENGTH) { - throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_LENGTH)); + throw LOGGER.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_LENGTH)); } else if (applicationId.contains(" ")) { - throw logger.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE)); + throw LOGGER.logExceptionAsError(new IllegalArgumentException(INVALID_APPLICATION_ID_SPACE)); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java index c20f2c1796f83..74246754ed7f3 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/CoreUtils.java @@ -36,6 +36,8 @@ * This class contains utility methods useful for building client libraries. */ public final class CoreUtils { + // CoreUtils is a commonly used utility, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(CoreUtils.class); private static final String COMMA = ","; private static final Charset UTF_32BE = Charset.forName("UTF-32BE"); private static final Charset UTF_32LE = Charset.forName("UTF-32LE"); @@ -202,7 +204,6 @@ public static Publisher extractAndFetch(PagedResponse page, Context co * @return an immutable {@link Map}. */ public static Map getProperties(String propertiesFileName) { - ClientLogger logger = new ClientLogger(CoreUtils.class); try (InputStream inputStream = CoreUtils.class.getClassLoader() .getResourceAsStream(propertiesFileName)) { if (inputStream != null) { @@ -213,7 +214,7 @@ public static Map getProperties(String propertiesFileName) { entry -> (String) entry.getValue()))); } } catch (IOException ex) { - logger.warning("Failed to get properties from " + propertiesFileName, ex); + LOGGER.warning("Failed to get properties from " + propertiesFileName, ex); } return Collections.emptyMap(); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/HttpClientOptions.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/HttpClientOptions.java index 7c68cd5591034..1f9e8dba361b4 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/HttpClientOptions.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/HttpClientOptions.java @@ -31,22 +31,21 @@ public final class HttpClientOptions extends ClientOptions { private static final Duration DEFAULT_CONNECTION_IDLE_TIMEOUT = Duration.ofSeconds(60); private static final Duration NO_TIMEOUT = Duration.ZERO; + private static final ClientLogger LOGGER = new ClientLogger(HttpClientOptions.class); + static { - ClientLogger logger = new ClientLogger(HttpClientOptions.class); Configuration configuration = Configuration.getGlobalConfiguration(); DEFAULT_CONNECT_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, - PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), logger); + PROPERTY_AZURE_REQUEST_CONNECT_TIMEOUT, Duration.ofSeconds(10), LOGGER); DEFAULT_WRITE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_WRITE_TIMEOUT, - Duration.ofSeconds(60), logger); + Duration.ofSeconds(60), LOGGER); DEFAULT_RESPONSE_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, - PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, Duration.ofSeconds(60), logger); + PROPERTY_AZURE_REQUEST_RESPONSE_TIMEOUT, Duration.ofSeconds(60), LOGGER); DEFAULT_READ_TIMEOUT = getDefaultTimeoutFromEnvironment(configuration, PROPERTY_AZURE_REQUEST_READ_TIMEOUT, - Duration.ofSeconds(60), logger); + Duration.ofSeconds(60), LOGGER); } - private final ClientLogger logger = new ClientLogger(HttpClientOptions.class); - private ProxyOptions proxyOptions; private Configuration configuration; private Duration connectTimeout; @@ -304,7 +303,7 @@ public Duration getReadTimeout() { */ public HttpClientOptions setMaximumConnectionPoolSize(Integer maximumConnectionPoolSize) { if (maximumConnectionPoolSize != null && maximumConnectionPoolSize <= 0) { - throw logger.logExceptionAsError( + throw LOGGER.logExceptionAsError( new IllegalArgumentException("'maximumConnectionPoolSize' cannot be less than 1.")); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByItemIterable.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByItemIterable.java index 049e937698663..c6c798fde4082 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByItemIterable.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByItemIterable.java @@ -44,13 +44,16 @@ public Iterator iterator() { private static final class ContinuablePagedByItemIterator> extends ContinuablePagedByIteratorBase { + // ContinuablePagedByItemIterator is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedByItemIterator.class); + private volatile Queue> pages = new ConcurrentLinkedQueue<>(); private volatile Iterator currentPage; ContinuablePagedByItemIterator(PageRetriever pageRetriever, C continuationToken, Predicate continuationPredicate, Integer preferredPageSize) { super(pageRetriever, new ContinuationState<>(continuationToken, continuationPredicate), preferredPageSize, - new ClientLogger(ContinuablePagedByItemIterator.class)); + LOGGER); requestPage(); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByPageIterable.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByPageIterable.java index b1ab8321f3f59..61b2666a56af7 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByPageIterable.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedByPageIterable.java @@ -44,12 +44,15 @@ public Iterator

iterator() { private static final class ContinuablePagedByPageIterator> extends ContinuablePagedByIteratorBase { + // ContinuablePagedByPageIterator is a commonly used class, use static logger. + private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedByPageIterator.class); + private volatile Queue

pages = new ConcurrentLinkedQueue<>(); ContinuablePagedByPageIterator(PageRetriever pageRetriever, C continuationToken, Predicate continuationPredicate, Integer preferredPageSize) { super(pageRetriever, new ContinuationState<>(continuationToken, continuationPredicate), preferredPageSize, - new ClientLogger(ContinuablePagedByPageIterator.class)); + LOGGER); requestPage(); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedFluxCore.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedFluxCore.java index f7b69b94712a4..1fc65eb065212 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedFluxCore.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/paging/ContinuablePagedFluxCore.java @@ -134,7 +134,8 @@ */ public abstract class ContinuablePagedFluxCore> extends ContinuablePagedFlux { - private final ClientLogger logger = new ClientLogger(ContinuablePagedFluxCore.class); + // ContinuablePagedFluxCore is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(ContinuablePagedFluxCore.class); final Supplier> pageRetrieverProvider; final Integer defaultPageSize; @@ -176,7 +177,7 @@ protected ContinuablePagedFluxCore(Supplier> pageRetrieverPr this.pageRetrieverProvider = Objects.requireNonNull(pageRetrieverProvider, "'pageRetrieverProvider' function cannot be null."); if (pageSize != null && pageSize <= 0) { - throw logger.logExceptionAsError( + throw LOGGER.logExceptionAsError( new IllegalArgumentException("'pageSize' must be greater than 0 required but provided: " + pageSize)); } this.defaultPageSize = pageSize; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/AsyncPollResponse.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/AsyncPollResponse.java index e84f97788de9e..9ae1d1c6437bc 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/AsyncPollResponse.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/AsyncPollResponse.java @@ -16,7 +16,7 @@ * AsyncPollResponse represents an event emitted by the {@link PollerFlux} that asynchronously polls * a long-running operation (LRO). An AsyncPollResponse event provides information such as the current * {@link LongRunningOperationStatus status} of the LRO, any {@link #getValue value} returned - * in the poll, as well as other useful information provided by the service. + * by the poll, as well as other useful information provided by the service. * AsyncPollResponse also exposes {@link #cancelOperation} method to cancel the long-running operation * from reactor operator chain and {@link #getFinalResult()} method that returns final result of * the long-running operation. @@ -25,7 +25,8 @@ * @param The type of the final result of long-running operation. */ public final class AsyncPollResponse { - private final ClientLogger logger = new ClientLogger(AsyncPollResponse.class); + // AsyncPollResponse is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(AsyncPollResponse.class); private final PollingContext pollingContext; private final BiFunction, PollResponse, Mono> cancellationOperation; private final Function, Mono> fetchResultOperation; @@ -79,7 +80,7 @@ public Mono cancelOperation() { return this.cancellationOperation .apply(this.pollingContext, this.pollingContext.getActivationResponse()); } catch (RuntimeException re) { - return FluxUtil.monoError(logger, re); + return FluxUtil.monoError(LOGGER, re); } }); } @@ -98,7 +99,7 @@ public Mono getFinalResult() { return this.fetchResultOperation .apply(this.pollingContext); } catch (RuntimeException re) { - return FluxUtil.monoError(logger, re); + return FluxUtil.monoError(LOGGER, re); } } }); diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/ChainedPollingStrategy.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/ChainedPollingStrategy.java index 41dbb324c25d6..8fff900e4c3ae 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/ChainedPollingStrategy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/ChainedPollingStrategy.java @@ -24,7 +24,7 @@ * kept */ public final class ChainedPollingStrategy implements PollingStrategy { - private final ClientLogger logger = new ClientLogger(ChainedPollingStrategy.class); + private static final ClientLogger LOGGER = new ClientLogger(ChainedPollingStrategy.class); private final List> pollingStrategies; private PollingStrategy pollableStrategy = null; @@ -38,7 +38,7 @@ public final class ChainedPollingStrategy implements PollingStrategy public ChainedPollingStrategy(List> strategies) { Objects.requireNonNull(strategies, "'strategies' cannot be null."); if (strategies.isEmpty()) { - throw logger.logExceptionAsError(new IllegalArgumentException("'strategies' cannot be empty.")); + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'strategies' cannot be empty.")); } this.pollingStrategies = Collections.unmodifiableList(strategies); } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/DefaultSyncPoller.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/DefaultSyncPoller.java index 804df297ff7c6..14cf03fe13871 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/DefaultSyncPoller.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/DefaultSyncPoller.java @@ -25,7 +25,7 @@ * @param The type of the final result of the long running operation */ final class DefaultSyncPoller implements SyncPoller { - private final ClientLogger logger = new ClientLogger(DefaultSyncPoller.class); + private static final ClientLogger LOGGER = new ClientLogger(DefaultSyncPoller.class); private final Function, Mono>> pollOperation; private final BiFunction, PollResponse, Mono> cancelOperation; private final Function, Mono> fetchResultOperation; @@ -59,7 +59,7 @@ final class DefaultSyncPoller implements SyncPoller { Function, Mono> fetchResultOperation) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.isNegative() || pollInterval.isZero()) { - throw logger.logExceptionAsWarning(new IllegalArgumentException( + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'defaultPollInterval' is not allowed.")); } this.pollInterval = pollInterval; @@ -147,7 +147,7 @@ public PollResponse waitUntil(LongRunningOperationStatus statusToWaitFor) { public PollResponse waitUntil(Duration timeout, LongRunningOperationStatus statusToWaitFor) { Objects.requireNonNull(timeout, "'timeout' cannot be null."); if (timeout.isNegative() || timeout.isZero()) { - throw logger.logExceptionAsWarning(new IllegalArgumentException( + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for timeout is not allowed.")); } Objects.requireNonNull(statusToWaitFor, "'statusToWaitFor' cannot be null."); @@ -213,7 +213,7 @@ public void cancelOperation() { public SyncPoller setPollInterval(Duration pollInterval) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.isNegative() || pollInterval.isZero()) { - throw logger.logExceptionAsWarning(new IllegalArgumentException( + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'pollInterval' is not allowed.")); } this.pollInterval = pollInterval; diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/LocationPollingStrategy.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/LocationPollingStrategy.java index 92af4ca0bb978..87071cc32697e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/LocationPollingStrategy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/LocationPollingStrategy.java @@ -36,7 +36,7 @@ public class LocationPollingStrategy implements PollingStrategy { private static final ObjectSerializer DEFAULT_SERIALIZER = new DefaultJsonSerializer(); - private final ClientLogger logger = new ClientLogger(LocationPollingStrategy.class); + private static final ClientLogger LOGGER = new ClientLogger(LocationPollingStrategy.class); private final HttpPipeline httpPipeline; private final ObjectSerializer serializer; @@ -71,7 +71,7 @@ public Mono canPoll(Response initialResponse) { new URL(locationHeader.getValue()); return Mono.just(true); } catch (MalformedURLException e) { - logger.info("Failed to parse Location header into a URL.", e); + LOGGER.info("Failed to parse Location header into a URL.", e); return Mono.just(false); } } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollerFlux.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollerFlux.java index 036b45121bf29..d1a6443dcaee4 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollerFlux.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollerFlux.java @@ -235,8 +235,8 @@ * @param The type of the final result of long running operation. */ public final class PollerFlux extends Flux> { - - private final ClientLogger logger = new ClientLogger(PollerFlux.class); + // PollerFlux is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(PollerFlux.class); private final PollingContext rootContext = new PollingContext<>(); private final Function, Mono>> pollOperation; private final BiFunction, PollResponse, Mono> cancelOperation; @@ -272,7 +272,7 @@ public PollerFlux(Duration pollInterval, Function, Mono> fetchResultOperation) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.compareTo(Duration.ZERO) <= 0) { - throw logger.logExceptionAsWarning(new IllegalArgumentException( + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'defaultPollInterval' is not allowed.")); } this.pollInterval = pollInterval; @@ -384,7 +384,7 @@ private PollerFlux(Duration pollInterval, boolean ignored) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.isNegative() || pollInterval.isZero()) { - throw logger.logExceptionAsWarning(new IllegalArgumentException( + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'pollInterval' is not allowed.")); } this.pollInterval = pollInterval; @@ -428,7 +428,7 @@ public static PollerFlux error(Exception ex) { public PollerFlux setPollInterval(Duration pollInterval) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.isNegative() || pollInterval.isZero()) { - throw logger.logExceptionAsWarning(new IllegalArgumentException( + throw LOGGER.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'pollInterval' is not allowed.")); } this.pollInterval = pollInterval; @@ -589,7 +589,7 @@ Mono getMono() { // 1. remove guard so that future subscriber can retry activation. // 2. forward error to current subscriber. this.guardActivation.set(false); - return FluxUtil.monoError(logger, e); + return FluxUtil.monoError(LOGGER, e); } return activationMono .map(this.activationPollResponseMapper) diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingContext.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingContext.java index 721dbb5148c19..6cd090f1fa64e 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingContext.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/polling/PollingContext.java @@ -17,7 +17,8 @@ * @param the type of the poll response. */ public final class PollingContext { - private final ClientLogger logger = new ClientLogger(PollingContext.class); + // PollingContext is a commonly used class, use a static logger. + private static final ClientLogger LOGGER = new ClientLogger(PollingContext.class); private final Map map; private volatile PollResponse activationResponse; private volatile PollResponse latestResponse; @@ -79,9 +80,8 @@ void setLatestResponse(PollResponse latestResponse) { */ void setOnetimeActivationResponse(PollResponse activationResponse) { if (this.activationResponse != null) { - throw logger - .logExceptionAsError(new IllegalStateException( - "setOnetimeActivationResponse can be called only once.")); + throw LOGGER.logExceptionAsError(new IllegalStateException( + "setOnetimeActivationResponse can be called only once.")); } else { this.activationResponse = activationResponse; this.latestResponse = this.activationResponse;