Skip to content

Commit

Permalink
feat: use SLF4J for logging
Browse files Browse the repository at this point in the history
  • Loading branch information
ttosta-google committed Nov 10, 2023
1 parent f94a8fd commit 383ddaa
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 43 deletions.
28 changes: 26 additions & 2 deletions core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

<properties>
<assembly.skipAssembly>false</assembly.skipAssembly>
<slf4j.version>2.0.9</slf4j.version>
</properties>

<dependencyManagement>
Expand Down Expand Up @@ -124,8 +125,8 @@
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.16.0</version>
</dependency>
<version>1.16.0</version>
</dependency>
</dependencies>
</dependencyManagement>

Expand Down Expand Up @@ -285,6 +286,19 @@
<scope>test</scope>
</dependency>

<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>

</dependencies>

<build>
Expand All @@ -301,6 +315,16 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<configuration>
<usedDependencies>
<!-- This dependency is not used at compile-time. -->
<dependency>org.slf4j:slf4j-jdk14</dependency>
</usedDependencies>
</configuration>
</plugin>
</plugins>
</build>

Expand Down
9 changes: 5 additions & 4 deletions core/src/main/java/com/google/cloud/sql/core/Connector.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@
import java.net.Socket;
import java.security.KeyPair;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocket;
import jnr.unixsocket.UnixSocketAddress;
import jnr.unixsocket.UnixSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class Connector {
private static final Logger logger = Logger.getLogger(Connector.class.getName());
private static final Logger logger = LoggerFactory.getLogger(Connector.class);

private final DefaultConnectionInfoRepository adminApi;
private final CredentialFactory instanceCredentialFactory;
Expand Down Expand Up @@ -80,7 +81,7 @@ private String getUnixSocketArg(ConnectionConfig config) {
} else if (System.getenv("CLOUD_SQL_FORCE_UNIX_SOCKET") != null) {
// If the deprecated env var is set, warn and use `/cloudsql/INSTANCE_CONNECTION_NAME`
// A socket factory is provided at this path for GAE, GCF, and Cloud Run
logger.warning(
logger.debug(
String.format(
"\"CLOUD_SQL_FORCE_UNIX_SOCKET\" env var has been deprecated. Please use"
+ " '%s=\"/cloudsql/INSTANCE_CONNECTION_NAME\"' property in your JDBC url"
Expand All @@ -100,7 +101,7 @@ Socket connect(ConnectionConfig config) throws IOException {
if (unixPathSuffix != null && !unixSocket.endsWith(unixPathSuffix)) {
unixSocket = unixSocket + unixPathSuffix;
}
logger.info(
logger.debug(
String.format(
"Connecting to Cloud SQL instance [%s] via unix socket at %s.",
config.getCloudSqlInstance(), unixSocket));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Optional;
import java.util.logging.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* DefaultAccessTokenSupplier produces access tokens using credentials produced by this connector's
* configured HttpRequestInitializer.
*/
class DefaultAccessTokenSupplier implements AccessTokenSupplier {

private static final Logger logger = Logger.getLogger(DefaultAccessTokenSupplier.class.getName());
private static final Logger logger = LoggerFactory.getLogger(DefaultAccessTokenSupplier.class);

private static final String SQL_LOGIN_SCOPE = "https://www.googleapis.com/auth/sqlservice.login";

Expand Down Expand Up @@ -91,7 +92,7 @@ public Optional<AccessToken> get() throws IOException {
|| "".equals(credentials.getAccessToken().getTokenValue())) {

String errorMessage = "Access Token has length of zero";
logger.warning(errorMessage);
logger.debug(errorMessage);

throw new IllegalStateException(errorMessage);
}
Expand All @@ -118,7 +119,7 @@ public Optional<AccessToken> get() throws IOException {
if (downscoped.getAccessToken() == null
|| "".equals(downscoped.getAccessToken().getTokenValue())) {
String errorMessage = "Downscoped access token has length of zero";
logger.warning(errorMessage);
logger.debug(errorMessage);

throw new IllegalStateException(
errorMessage
Expand Down Expand Up @@ -161,7 +162,7 @@ private void validateAccessTokenExpiration(AccessToken accessToken) {
+ nowFormat
+ " Expiration = "
+ expirationFormat;
logger.warning(errorMessage);
logger.debug(errorMessage);
throw new IllegalStateException(errorMessage);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,17 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Logger;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Class that encapsulates all logic for interacting with SQLAdmin API. */
class DefaultConnectionInfoRepository implements ConnectionInfoRepository {

private static final Logger logger =
Logger.getLogger(DefaultConnectionInfoRepository.class.getName());
LoggerFactory.getLogger(DefaultConnectionInfoRepository.class);
private final SQLAdmin apiClient;

DefaultConnectionInfoRepository(SQLAdmin apiClient) {
Expand Down Expand Up @@ -149,7 +150,7 @@ public ListenableFuture<ConnectionInfo> getConnectionInfo(
.orElse(x509Certificate.getNotAfter().toInstant());
}

logger.fine(String.format("[%s] INSTANCE DATA DONE", instanceName));
logger.debug(String.format("[%s] INSTANCE DATA DONE", instanceName));

return new ConnectionInfo(
Futures.getDone(metadataFuture),
Expand All @@ -159,7 +160,7 @@ public ListenableFuture<ConnectionInfo> getConnectionInfo(
executor);

done.addListener(
() -> logger.fine(String.format("[%s] ALL FUTURES DONE", instanceName)), executor);
() -> logger.debug(String.format("[%s] ALL FUTURES DONE", instanceName)), executor);
return done;
}

Expand Down Expand Up @@ -226,7 +227,7 @@ private InstanceMetadata fetchMetadata(CloudSqlInstanceName instanceName, AuthTy
Certificate instanceCaCertificate =
createCertificate(instanceMetadata.getServerCaCert().getCert());

logger.fine(String.format("[%s] METADATA DONE", instanceName));
logger.debug(String.format("[%s] METADATA DONE", instanceName));

return new InstanceMetadata(ipAddrs, instanceCaCertificate);
} catch (CertificateException ex) {
Expand Down Expand Up @@ -297,7 +298,7 @@ private Certificate fetchEphemeralCertificate(
ex);
}

logger.fine(String.format("[%s %d] CERT DONE", instanceName, Thread.currentThread().getId()));
logger.debug(String.format("[%s %d] CERT DONE", instanceName, Thread.currentThread().getId()));

return ephemeralCertificate;
}
Expand Down Expand Up @@ -343,14 +344,14 @@ private SslData createSslData(
+ " using IAM authentication",
ex);
} else {
logger.warning("TLSv1.3 is not supported for your Java version, fallback to TLSv1.2");
logger.debug("TLSv1.3 is not supported for your Java version, fallback to TLSv1.2");
sslContext = SSLContext.getInstance("TLSv1.2");
}
}

sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

logger.fine(
logger.debug(
String.format("[%s %d] SSL CONTEXT", instanceName, Thread.currentThread().getId()));

return new SslData(sslContext, kmf, tmf);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.logging.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* InternalConnectorRegistry keeps track of connectors. This class should not be used directly, but
Expand All @@ -46,7 +47,7 @@
public final class InternalConnectorRegistry {

static final long DEFAULT_MAX_REFRESH_MS = 30000;
private static final Logger logger = Logger.getLogger(InternalConnectorRegistry.class.getName());
private static final Logger logger = LoggerFactory.getLogger(InternalConnectorRegistry.class);

static final int DEFAULT_SERVER_PROXY_PORT = 3307;
private static final int RSA_KEY_SIZE = 2048;
Expand Down Expand Up @@ -91,7 +92,7 @@ public final class InternalConnectorRegistry {
/** Returns the {@link InternalConnectorRegistry} singleton. */
public static synchronized InternalConnectorRegistry getInstance() {
if (internalConnectorRegistry == null) {
logger.info("First Cloud SQL connection, generating RSA key pair.");
logger.debug("First Cloud SQL connection, generating RSA key pair.");

CredentialFactoryProvider credentialFactoryProvider = new CredentialFactoryProvider();

Expand Down
19 changes: 9 additions & 10 deletions core/src/main/java/com/google/cloud/sql/core/Refresher.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Handles periodic refresh operations for an instance. */
class Refresher {
private static final Logger logger = Logger.getLogger(Refresher.class.getName());
private static final Logger logger = LoggerFactory.getLogger(Refresher.class);

private final ListeningScheduledExecutorService executor;

Expand Down Expand Up @@ -147,7 +147,7 @@ void forceRefresh() {
next.cancel(false);
}

logger.fine(
logger.debug(
String.format(
"[%s] Force Refresh: the next refresh operation was cancelled."
+ " Scheduling new refresh operation immediately.",
Expand All @@ -172,11 +172,11 @@ private ListenableFuture<ConnectionInfo> startRefreshAttempt() {
refreshRunning = true;
}

logger.fine(String.format("[%s] Refresh Operation: Acquiring rate limiter permit.", name));
logger.debug(String.format("[%s] Refresh Operation: Acquiring rate limiter permit.", name));
ListenableFuture<?> delay = rateLimiter.acquireAsync(executor);
delay.addListener(
() ->
logger.fine(
logger.debug(
String.format("[%s] Refresh Operation: Rate limiter permit acquired.", name)),
executor);

Expand All @@ -195,14 +195,14 @@ private ListenableFuture<ConnectionInfo> handleRefreshResult(
// This will throw an exception if the refresh attempt has failed.
ConnectionInfo info = connectionInfoFuture.get();

logger.fine(
logger.debug(
String.format(
"[%s] Refresh Operation: Completed refresh with new certificate expiration at %s.",
name, info.getExpiration().toString()));
long secondsToRefresh =
refreshCalculator.calculateSecondsUntilNextRefresh(Instant.now(), info.getExpiration());

logger.fine(
logger.debug(
String.format(
"[%s] Refresh Operation: Next operation scheduled at %s.",
name,
Expand All @@ -229,8 +229,7 @@ private ListenableFuture<ConnectionInfo> handleRefreshResult(
}

} catch (ExecutionException | InterruptedException e) {
logger.log(
Level.FINE,
logger.info(
String.format(
"[%s] Refresh Operation: Failed! Starting next refresh operation immediately.", name),
e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,17 @@
import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultConnectionInfoCacheConcurrencyTest {

public static final int DEFAULT_WAIT = 200;

private static final Logger logger =
Logger.getLogger(DefaultConnectionInfoCacheConcurrencyTest.class.getName());
LoggerFactory.getLogger(DefaultConnectionInfoCacheConcurrencyTest.class);
public static final int FORCE_REFRESH_COUNT = 10;

private static class TestCredentialFactory implements CredentialFactory, HttpRequestInitializer {
Expand Down Expand Up @@ -98,7 +100,7 @@ public void testForceRefreshDoesNotCauseADeadlockOrBrokenRefreshLoop() throws Ex
int brokenLoop = 0;
for (DefaultConnectionInfoCache i : caches) {
if (i.getCurrent().isDone() && i.getNext().isDone()) {
logger.warning("No future scheduled thing for instance " + i.getInstanceName());
logger.debug("No future scheduled thing for instance " + i.getInstanceName());
brokenLoop++;
}
}
Expand All @@ -120,7 +122,7 @@ private Thread startForceRefreshThread(DefaultConnectionInfoCache connectionInfo
logger.info("Exception in force refresh loop.");
}
}
logger.info("Done spamming");
logger.debug("Done spamming");
};

Thread t = new Thread(forceRefreshRepeat);
Expand Down
6 changes: 6 additions & 0 deletions jdbc/mariadb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,12 @@
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>3.3.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
Expand Down
28 changes: 28 additions & 0 deletions jdbc/postgres/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,24 @@

<properties>
<assembly.skipAssembly>false</assembly.skipAssembly>
<slf4j.version>2.0.9</slf4j.version>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<configuration>
<usedDependencies>
<!-- This dependency is not used at compile-time. -->
<dependency>org.slf4j:slf4j-jdk14</dependency>
</usedDependencies>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
Expand Down Expand Up @@ -154,6 +170,18 @@
<version>4.0.3</version>
<scope>test</scope>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>

<profiles>
Expand Down
Loading

0 comments on commit 383ddaa

Please sign in to comment.