diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java
index d11cfb7bd329..f26da41f035c 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java
@@ -52,7 +52,6 @@
import com.google.cloud.bigquery.storage.v1.BigQueryWriteClient;
import com.google.cloud.bigquery.storage.v1.BigQueryWriteSettings;
import com.google.cloud.http.HttpTransportOptions;
-import com.google.cloud.logging.Logging;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
@@ -1597,6 +1596,7 @@ private OpenTelemetry getOpenTelemetryInstance() {
this.sslTrustStoreType,
this.sslTrustStoreProvider)
.setHttpTransportFactory(this.httpTransportOptions.getHttpTransportFactory())
+ .setTransportChannelProvider(this.transportChannelProvider)
.build();
OpenTelemetry openTelemetry =
@@ -1612,24 +1612,22 @@ private OpenTelemetry getOpenTelemetryInstance() {
this.openTelemetry = openTelemetry;
boolean hasExternalOtel = this.customOpenTelemetry != null || this.useGlobalOpenTelemetry;
- Logging localLoggingClient = null;
+ GcpLogWriter localLogWriter = null;
if (this.enableGcpLogExporter && !hasExternalOtel) {
- localLoggingClient =
- BigQueryJdbcOpenTelemetry.createLoggingClient(
- true,
- null,
+ localLogWriter =
+ GcpLogWriter.create(
this.gcpTelemetryCredentials,
effectiveProjectId,
this.credentials,
this.headerProvider,
- this.universeDomain);
+ telemetryTransportConfig);
}
if (this.enableGcpLogExporter || hasExternalOtel) {
BigQueryJdbcOpenTelemetry.registerConnection(
this.connectionId,
openTelemetry,
- localLoggingClient,
+ localLogWriter,
this.enableGcpLogExporter && !hasExternalOtel);
}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java
index adb4b122cfad..3cb1fa9b4d4e 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetry.java
@@ -16,7 +16,7 @@
package com.google.cloud.bigquery.jdbc;
-import com.google.api.gax.rpc.HeaderProvider;
+import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.auth.Credentials;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.ComputeEngineCredentials;
@@ -24,8 +24,6 @@
import com.google.auth.oauth2.ImpersonatedCredentials;
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
-import com.google.cloud.logging.Logging;
-import com.google.cloud.logging.LoggingOptions;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.Hashing;
import io.opentelemetry.api.GlobalOpenTelemetry;
@@ -117,6 +115,7 @@ static final class TelemetryTransportConfig {
final String sslTrustStoreType;
final String sslTrustStoreProvider;
final HttpTransportFactory httpTransportFactory;
+ final TransportChannelProvider transportChannelProvider;
private TelemetryTransportConfig(Builder builder) {
this.universeDomain = builder.universeDomain;
@@ -129,6 +128,7 @@ private TelemetryTransportConfig(Builder builder) {
this.sslTrustStoreType = builder.sslTrustStoreType;
this.sslTrustStoreProvider = builder.sslTrustStoreProvider;
this.httpTransportFactory = builder.httpTransportFactory;
+ this.transportChannelProvider = builder.transportChannelProvider;
}
static Builder builder() {
@@ -144,6 +144,7 @@ static final class Builder {
private String sslTrustStoreType;
private String sslTrustStoreProvider;
private HttpTransportFactory httpTransportFactory;
+ private TransportChannelProvider transportChannelProvider;
Builder setUniverseDomain(String universeDomain) {
this.universeDomain = universeDomain;
@@ -173,6 +174,11 @@ Builder setHttpTransportFactory(HttpTransportFactory httpTransportFactory) {
return this;
}
+ Builder setTransportChannelProvider(TransportChannelProvider transportChannelProvider) {
+ this.transportChannelProvider = transportChannelProvider;
+ return this;
+ }
+
TelemetryTransportConfig build() {
return new TelemetryTransportConfig(this);
}
@@ -236,13 +242,13 @@ private static final class CachedSdk {
static class TelemetryConfig {
final OpenTelemetry openTelemetry;
- final Logging loggingClient;
+ final GcpLogWriter gcpLogWriter;
final boolean useDirectGcpLogging;
TelemetryConfig(
- OpenTelemetry openTelemetry, Logging loggingClient, Boolean useDirectGcpLogging) {
+ OpenTelemetry openTelemetry, GcpLogWriter gcpLogWriter, Boolean useDirectGcpLogging) {
this.openTelemetry = openTelemetry;
- this.loggingClient = loggingClient;
+ this.gcpLogWriter = gcpLogWriter;
this.useDirectGcpLogging = useDirectGcpLogging != null ? useDirectGcpLogging : false;
}
}
@@ -273,78 +279,23 @@ public static synchronized void ensureGlobalHandlerAttached() {
public static void registerConnection(
String connectionId,
OpenTelemetry openTelemetry,
- Logging loggingClient,
+ GcpLogWriter gcpLogWriter,
Boolean useDirectGcpLogging) {
connectionConfigs.put(
- connectionId, new TelemetryConfig(openTelemetry, loggingClient, useDirectGcpLogging));
+ connectionId, new TelemetryConfig(openTelemetry, gcpLogWriter, useDirectGcpLogging));
}
public static void unregisterConnection(String connectionId) {
TelemetryConfig config = connectionConfigs.remove(connectionId);
- if (config != null && config.loggingClient != null) {
+ if (config != null && config.gcpLogWriter != null) {
try {
- config.loggingClient.close();
+ config.gcpLogWriter.close();
} catch (Exception e) {
LOG.warning("Failed to close Logging client during unregister: %s", e.getMessage());
}
}
}
- public static Logging createLoggingClient(
- boolean enableGcpLogExporter,
- OpenTelemetry customOpenTelemetry,
- String effectiveCredentials,
- String effectiveProjectId,
- Credentials fallbackCredentials,
- HeaderProvider headerProvider) {
- return createLoggingClient(
- enableGcpLogExporter,
- customOpenTelemetry,
- effectiveCredentials,
- effectiveProjectId,
- fallbackCredentials,
- headerProvider,
- null);
- }
-
- static Logging createLoggingClient(
- boolean enableGcpLogExporter,
- OpenTelemetry customOpenTelemetry,
- String effectiveCredentials,
- String effectiveProjectId,
- Credentials fallbackCredentials,
- HeaderProvider headerProvider,
- String universeDomain) {
-
- if (!enableGcpLogExporter || customOpenTelemetry != null) {
- return null;
- }
-
- try {
- Credentials credentials;
- if (effectiveCredentials != null) {
- credentials = resolveCredentialsFromString(effectiveCredentials, null, null);
- } else {
- credentials = fallbackCredentials;
- }
-
- LoggingOptions.Builder loggingOptionsBuilder =
- LoggingOptions.newBuilder().setProjectId(effectiveProjectId);
- if (credentials != null) {
- loggingOptionsBuilder.setCredentials(credentials);
- }
- if (headerProvider != null) {
- loggingOptionsBuilder.setHeaderProvider(headerProvider);
- }
- if (universeDomain != null) {
- loggingOptionsBuilder.setUniverseDomain(universeDomain);
- }
- return loggingOptionsBuilder.build().getService();
- } catch (Exception e) {
- throw new BigQueryJdbcRuntimeException("Failed to initialize Logging client", e);
- }
- }
-
public static void releaseSdk(OpenTelemetry openTelemetry) {
if (openTelemetry == null || openTelemetry == OpenTelemetry.noop()) {
return;
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/GcpLogWriter.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/GcpLogWriter.java
new file mode 100644
index 000000000000..d884b61cfbd9
--- /dev/null
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/GcpLogWriter.java
@@ -0,0 +1,373 @@
+/*
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud.bigquery.jdbc;
+
+import com.google.api.MonitoredResource;
+import com.google.api.core.ApiFuture;
+import com.google.api.core.ApiFutureCallback;
+import com.google.api.core.ApiFutures;
+import com.google.api.gax.batching.BatchingSettings;
+import com.google.api.gax.batching.FlowController;
+import com.google.api.gax.core.FixedCredentialsProvider;
+import com.google.api.gax.rpc.HeaderProvider;
+import com.google.auth.Credentials;
+import com.google.auth.oauth2.ServiceAccountCredentials;
+import com.google.cloud.ServiceOptions;
+import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
+import com.google.cloud.bigquery.jdbc.BigQueryJdbcOpenTelemetry.TelemetryTransportConfig;
+import com.google.cloud.logging.MonitoredResourceUtil;
+import com.google.cloud.logging.v2.LoggingClient;
+import com.google.cloud.logging.v2.LoggingSettings;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.logging.type.LogSeverity;
+import com.google.logging.v2.LogEntry;
+import com.google.logging.v2.LogName;
+import com.google.logging.v2.WriteLogEntriesRequest;
+import com.google.logging.v2.WriteLogEntriesResponse;
+import com.google.protobuf.Timestamp;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+/**
+ * Package-private direct Google Cloud Logging writer backed by the GAPIC {@link LoggingClient}.
+ *
+ *
Coordinates concurrent JUL log writes with connection teardown and enforces a bounded flush on
+ * close.
+ */
+class GcpLogWriter implements AutoCloseable {
+
+ static final String LOGGING_WRITE_SCOPE = "https://www.googleapis.com/auth/logging.write";
+ private static final long DEFAULT_FLUSH_TIMEOUT_MILLIS = 6_000L;
+ private static final BigQueryJdbcCustomLogger LOG =
+ new BigQueryJdbcCustomLogger(GcpLogWriter.class.getName());
+ private static final Object MONITORED_RESOURCE_LOCK = new Object();
+ private static final ConcurrentHashMap MONITORED_RESOURCE_CACHE =
+ new ConcurrentHashMap<>();
+ private static final ThreadLocal IN_WRITE = new ThreadLocal<>();
+
+ private final LoggingClient loggingClient;
+ private final String projectId;
+ private final MonitoredResource resource;
+ private final long flushTimeoutMillis;
+ private final ConcurrentHashMap> pendingWrites =
+ new ConcurrentHashMap<>();
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+ private final AtomicBoolean failureLogged = new AtomicBoolean(false);
+ private final AtomicInteger failedWrites = new AtomicInteger(0);
+ private final ReentrantReadWriteLock lifecycleLock = new ReentrantReadWriteLock();
+
+ GcpLogWriter(
+ LoggingClient loggingClient,
+ String projectId,
+ MonitoredResource resource,
+ long flushTimeoutMillis) {
+ this.loggingClient = loggingClient;
+ this.projectId = projectId;
+ this.resource = resource;
+ this.flushTimeoutMillis = flushTimeoutMillis;
+ }
+
+ static GcpLogWriter create(
+ String effectiveCredentials,
+ String effectiveProjectId,
+ Credentials fallbackCredentials,
+ HeaderProvider headerProvider,
+ TelemetryTransportConfig transportConfig) {
+ return create(
+ effectiveCredentials,
+ effectiveProjectId,
+ fallbackCredentials,
+ headerProvider,
+ transportConfig,
+ GcpLogWriter::detectMonitoredResource,
+ DEFAULT_FLUSH_TIMEOUT_MILLIS);
+ }
+
+ @VisibleForTesting
+ static GcpLogWriter create(
+ String effectiveCredentials,
+ String effectiveProjectId,
+ Credentials fallbackCredentials,
+ HeaderProvider headerProvider,
+ TelemetryTransportConfig transportConfig,
+ Function monitoredResourceProvider,
+ long flushTimeoutMillis) {
+ try {
+ String validatedUniverse =
+ BigQueryJdbcOpenTelemetry.validateNormalizedUniverseDomain(
+ transportConfig.universeDomain);
+ String targetUniverseDomain =
+ BigQueryJdbcOpenTelemetry.resolveTargetUniverseDomain(validatedUniverse);
+ Credentials credentials =
+ BigQueryJdbcOpenTelemetry.resolveTelemetryCredentials(
+ effectiveCredentials,
+ fallbackCredentials,
+ transportConfig,
+ targetUniverseDomain,
+ LOGGING_WRITE_SCOPE);
+
+ String resolvedProjectId = resolveLoggingProjectId(effectiveProjectId, credentials);
+ MonitoredResource monitoredResource = monitoredResourceProvider.apply(resolvedProjectId);
+
+ LoggingSettings.Builder settingsBuilder = LoggingSettings.newBuilder();
+ if (credentials != null) {
+ settingsBuilder.setCredentialsProvider(FixedCredentialsProvider.create(credentials));
+ }
+ if (headerProvider != null) {
+ settingsBuilder.setHeaderProvider(headerProvider);
+ }
+ if (validatedUniverse != null) {
+ settingsBuilder.setUniverseDomain(validatedUniverse);
+ }
+ if (transportConfig.transportChannelProvider != null) {
+ settingsBuilder.setTransportChannelProvider(transportConfig.transportChannelProvider);
+ }
+
+ BatchingSettings defaultBatchSettings =
+ settingsBuilder.writeLogEntriesSettings().getBatchingSettings();
+ settingsBuilder
+ .writeLogEntriesSettings()
+ .setBatchingSettings(
+ defaultBatchSettings.toBuilder()
+ .setFlowControlSettings(
+ defaultBatchSettings.getFlowControlSettings().toBuilder()
+ .setLimitExceededBehavior(FlowController.LimitExceededBehavior.Block)
+ .build())
+ .build());
+
+ LoggingClient loggingClient = LoggingClient.create(settingsBuilder.build());
+ return new GcpLogWriter(
+ loggingClient, resolvedProjectId, monitoredResource, flushTimeoutMillis);
+ } catch (BigQueryJdbcRuntimeException e) {
+ throw e;
+ } catch (Exception e) {
+ throw new BigQueryJdbcRuntimeException("Failed to initialize Logging client", e);
+ }
+ }
+
+ private static MonitoredResource detectMonitoredResource(String projectId) {
+ return getOrDetectMonitoredResource(
+ projectId,
+ id -> {
+ synchronized (MONITORED_RESOURCE_LOCK) {
+ return MonitoredResourceUtil.getResource(id, null).toPb();
+ }
+ });
+ }
+
+ @VisibleForTesting
+ static MonitoredResource getOrDetectMonitoredResource(
+ String projectId, Function detector) {
+ return MONITORED_RESOURCE_CACHE.computeIfAbsent(projectId, detector);
+ }
+
+ @VisibleForTesting
+ static void clearMonitoredResourceCacheForTest() {
+ MONITORED_RESOURCE_CACHE.clear();
+ }
+
+ private static String resolveLoggingProjectId(
+ String effectiveProjectId, Credentials credentials) {
+ return resolveLoggingProjectId(
+ effectiveProjectId, credentials, ServiceOptions::getDefaultProjectId);
+ }
+
+ @VisibleForTesting
+ static String resolveLoggingProjectId(
+ String effectiveProjectId,
+ Credentials credentials,
+ Supplier defaultProjectIdSupplier) {
+ if (effectiveProjectId != null && !effectiveProjectId.trim().isEmpty()) {
+ return effectiveProjectId.trim();
+ }
+ if (credentials instanceof ServiceAccountCredentials) {
+ String saProjectId = ((ServiceAccountCredentials) credentials).getProjectId();
+ if (saProjectId != null && !saProjectId.trim().isEmpty()) {
+ return saProjectId.trim();
+ }
+ }
+ String defaultProjectId = defaultProjectIdSupplier.get();
+ if (defaultProjectId != null && !defaultProjectId.trim().isEmpty()) {
+ return defaultProjectId.trim();
+ }
+ throw new BigQueryJdbcRuntimeException(
+ "A GCP project ID is required for Cloud Logging export.");
+ }
+
+ @VisibleForTesting
+ LoggingClient getLoggingClient() {
+ return loggingClient;
+ }
+
+ @VisibleForTesting
+ MonitoredResource getResource() {
+ return resource;
+ }
+
+ void write(
+ String logId,
+ LogSeverity severity,
+ Instant timestamp,
+ String message,
+ String traceId,
+ String spanId,
+ String connectionId) {
+ if (closed.get() || Boolean.TRUE.equals(IN_WRITE.get())) {
+ return;
+ }
+ IN_WRITE.set(true);
+ try {
+ lifecycleLock.readLock().lock();
+ try {
+ if (closed.get()) {
+ return;
+ }
+
+ LogEntry.Builder entryBuilder =
+ LogEntry.newBuilder()
+ .setLogName(LogName.ofProjectLogName(projectId, logId).toString())
+ .setResource(resource)
+ .setSeverity(severity)
+ .setTimestamp(
+ Timestamp.newBuilder()
+ .setSeconds(timestamp.getEpochSecond())
+ .setNanos(timestamp.getNano())
+ .build())
+ .setTextPayload(message)
+ .putLabels(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, connectionId);
+
+ if (traceId != null) {
+ entryBuilder.setTrace(String.format("projects/%s/traces/%s", projectId, traceId));
+ }
+ if (spanId != null) {
+ entryBuilder.setSpanId(spanId);
+ }
+
+ WriteLogEntriesRequest request =
+ WriteLogEntriesRequest.newBuilder()
+ .setPartialSuccess(true)
+ .addEntries(entryBuilder.build())
+ .build();
+
+ final Object pendingKey = new Object();
+ ApiFuture future =
+ loggingClient.writeLogEntriesCallable().futureCall(request);
+ pendingWrites.put(pendingKey, future);
+ ApiFutures.addCallback(
+ future,
+ new ApiFutureCallback() {
+ @Override
+ public void onSuccess(WriteLogEntriesResponse result) {
+ pendingWrites.remove(pendingKey);
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ pendingWrites.remove(pendingKey);
+ failedWrites.incrementAndGet();
+ if (failureLogged.compareAndSet(false, true)) {
+ LOG.warning(
+ "Failed to export log entry to Cloud Logging (further failures will be"
+ + " summarized on close): %s",
+ t.getMessage());
+ }
+ }
+ },
+ MoreExecutors.directExecutor());
+ } catch (RejectedExecutionException | IllegalStateException e) {
+ if (!closed.get()) {
+ throw e;
+ }
+ } finally {
+ lifecycleLock.readLock().unlock();
+ }
+ } finally {
+ IN_WRITE.remove();
+ }
+ }
+
+ void flush() {
+ flushInternal();
+ }
+
+ private boolean flushInternal() {
+ List> writesToFlush =
+ new ArrayList<>(pendingWrites.values());
+ if (writesToFlush.isEmpty()) {
+ return true;
+ }
+ try {
+ ApiFutures.successfulAsList(writesToFlush).get(flushTimeoutMillis, TimeUnit.MILLISECONDS);
+ return true;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ } catch (ExecutionException | TimeoutException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public void close() {
+ if (!closed.compareAndSet(false, true)) {
+ return;
+ }
+ boolean lockAcquired = false;
+ try {
+ lockAcquired = lifecycleLock.writeLock().tryLock(flushTimeoutMillis, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ if (!lockAcquired) {
+ pendingWrites.clear();
+ loggingClient.shutdownNow();
+ logDroppedWritesSummary();
+ return;
+ }
+ try {
+ boolean flushed = flushInternal();
+ pendingWrites.clear();
+ if (flushed) {
+ loggingClient.close();
+ } else {
+ loggingClient.shutdownNow();
+ }
+ } finally {
+ lifecycleLock.writeLock().unlock();
+ }
+ logDroppedWritesSummary();
+ }
+
+ private void logDroppedWritesSummary() {
+ int dropped = failedWrites.get();
+ if (dropped > 1) {
+ LOG.warning("Cloud Logging export dropped %d log write(s) before close.", dropped);
+ }
+ }
+}
diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java
index a2829814c7e7..1f8831f2156a 100644
--- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java
+++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java
@@ -16,9 +16,7 @@
package com.google.cloud.bigquery.jdbc;
-import com.google.cloud.logging.LogEntry;
-import com.google.cloud.logging.Logging;
-import com.google.cloud.logging.Payload;
+import com.google.logging.type.LogSeverity;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.common.AttributeKey;
@@ -31,7 +29,6 @@
import java.text.MessageFormat;
import java.time.Instant;
import java.util.Arrays;
-import java.util.Collections;
import java.util.logging.ErrorManager;
import java.util.logging.Handler;
import java.util.logging.Level;
@@ -88,8 +85,8 @@ public void publish(LogRecord record) {
return;
}
- if (config.useDirectGcpLogging && config.loggingClient != null) {
- publishToGcp(record, connectionId, config.loggingClient);
+ if (config.useDirectGcpLogging && config.gcpLogWriter != null) {
+ publishToGcp(record, connectionId, config.gcpLogWriter);
} else if (config.openTelemetry != null) {
publishToOTel(record, connectionId, config.openTelemetry);
}
@@ -99,7 +96,7 @@ public void publish(LogRecord record) {
}
}
- private void publishToGcp(LogRecord record, String connectionId, Logging loggingClient) {
+ private void publishToGcp(LogRecord record, String connectionId, GcpLogWriter logWriter) {
Context context = Context.current();
SpanContext spanContext = Span.fromContext(context).getSpanContext();
String traceId = spanContext.isValid() ? spanContext.getTraceId() : null;
@@ -113,32 +110,27 @@ private void publishToGcp(LogRecord record, String connectionId, Logging logging
}
String formatted = formatMessage(record);
- LogEntry.Builder builder =
- LogEntry.newBuilder(Payload.StringPayload.of(formatted != null ? formatted : ""))
- .setSeverity(mapGcpSeverity(record.getLevel()))
- .setTimestamp(Instant.ofEpochMilli(record.getMillis()))
- .setLogName(logId);
+ logWriter.write(
+ logId,
+ mapGcpSeverity(record.getLevel()),
+ Instant.ofEpochMilli(record.getMillis()),
+ formatted != null ? formatted : "",
+ traceId,
+ spanId,
+ connectionId);
+ }
- if (traceId != null) {
- builder.setTrace(traceId);
+ private LogSeverity mapGcpSeverity(Level level) {
+ if (level == Level.SEVERE) {
+ return LogSeverity.ERROR;
}
- if (spanId != null) {
- builder.setSpanId(spanId);
+ if (level == Level.WARNING) {
+ return LogSeverity.WARNING;
}
- if (connectionId != null) {
- builder.addLabel(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, connectionId);
+ if (level == Level.INFO || level == Level.CONFIG) {
+ return LogSeverity.INFO;
}
-
- loggingClient.write(Collections.singleton(builder.build()));
- }
-
- private com.google.cloud.logging.Severity mapGcpSeverity(Level level) {
- if (level == Level.SEVERE) return com.google.cloud.logging.Severity.ERROR;
- if (level == Level.WARNING) return com.google.cloud.logging.Severity.WARNING;
- if (level == Level.INFO) return com.google.cloud.logging.Severity.INFO;
- if (level == Level.CONFIG) return com.google.cloud.logging.Severity.INFO;
- if (level == Level.FINE) return com.google.cloud.logging.Severity.DEBUG;
- return com.google.cloud.logging.Severity.DEBUG;
+ return LogSeverity.DEBUG;
}
private void publishToOTel(LogRecord record, String connectionId, OpenTelemetry openTelemetry) {
@@ -217,9 +209,9 @@ private static boolean hasPositionalPlaceholder(String message) {
public void flush() {
for (BigQueryJdbcOpenTelemetry.TelemetryConfig config :
BigQueryJdbcOpenTelemetry.getRegisteredConfigs()) {
- if (config.useDirectGcpLogging && config.loggingClient != null) {
+ if (config.useDirectGcpLogging && config.gcpLogWriter != null) {
try {
- config.loggingClient.flush();
+ config.gcpLogWriter.flush();
} catch (Exception e) {
reportError("Error flushing log to OpenTelemetry/GCP", e, ErrorManager.FLUSH_FAILURE);
}
diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java
index d0beded46750..c974523f8890 100644
--- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java
+++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryConnectionTest.java
@@ -65,6 +65,7 @@
import com.google.cloud.bigquery.Schema;
import com.google.cloud.bigquery.TableResult;
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
+import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature;
import com.google.cloud.bigquery.jdbc.telemetry.v1.FeatureUsage;
import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager;
@@ -76,7 +77,6 @@
import com.google.cloud.bigquery.storage.v1.BigQueryReadSettings;
import com.google.cloud.bigquery.storage.v1.BigQueryWriteClient;
import com.google.cloud.bigquery.storage.v1.BigQueryWriteSettings;
-import com.google.cloud.logging.Logging;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.opentelemetry.api.OpenTelemetry;
@@ -665,7 +665,7 @@ public void testOpenTelemetryPrecedenceHierarchy(
OpenTelemetry mockCustomOtel = mock(OpenTelemetry.class);
OpenTelemetry mockGlobalOtel = mock(OpenTelemetry.class);
OpenTelemetry mockDriverManagedOtel = mock(OpenTelemetry.class);
- Logging mockLogging = mock(Logging.class);
+ GcpLogWriter mockLogWriter = mock(GcpLogWriter.class);
when(mockCustomOtel.getTracer(anyString())).thenReturn(mock(Tracer.class));
when(mockGlobalOtel.getTracer(anyString())).thenReturn(mock(Tracer.class));
when(mockDriverManagedOtel.getTracer(anyString())).thenReturn(mock(Tracer.class));
@@ -676,6 +676,7 @@ public void testOpenTelemetryPrecedenceHierarchy(
try (MockedStatic mockedOtel =
mockStatic(BigQueryJdbcOpenTelemetry.class);
+ MockedStatic mockedLogWriter = mockStatic(GcpLogWriter.class);
MockedStatic mockedAuth =
mockStatic(BigQueryJdbcOAuthUtility.class);
MockedStatic mockedCreds = mockStatic(GoogleCredentials.class)) {
@@ -700,12 +701,9 @@ public void testOpenTelemetryPrecedenceHierarchy(
.when(() -> BigQueryJdbcOAuthUtility.getCredentials(any(), any(), any(), any(), any()))
.thenReturn(mock(GoogleCredentials.class));
- mockedOtel
- .when(
- () ->
- BigQueryJdbcOpenTelemetry.createLoggingClient(
- anyBoolean(), any(), any(), any(), any(), any(), any()))
- .thenReturn(mockLogging);
+ mockedLogWriter
+ .when(() -> GcpLogWriter.create(any(), any(), any(), any(), any()))
+ .thenReturn(mockLogWriter);
// Stub getOpenTelemetry to return the expected mock based on inputs
mockedOtel
@@ -751,14 +749,14 @@ public void testOpenTelemetryPrecedenceHierarchy(
}
boolean expectUseDirectGcp = "DRIVER_MANAGED".equals(expectLog);
- Logging expectedLogClient = expectUseDirectGcp ? mockLogging : null;
+ GcpLogWriter expectedLogWriter = expectUseDirectGcp ? mockLogWriter : null;
mockedOtel.verify(
() ->
BigQueryJdbcOpenTelemetry.registerConnection(
anyString(),
eq(expectedOtelInstance),
- eq(expectedLogClient),
+ eq(expectedLogWriter),
eq(expectUseDirectGcp)));
}
}
@@ -2090,7 +2088,7 @@ public void testConcurrentGetWarningsAndReset_neverThrowsIndexOutOfBounds() thro
}
@Test
- public void testConnectionPropagatesUniverseProxyAndTrustStoreToTelemetryClient()
+ public void testConnectionPropagatesUniverseProxyAndTrustStoreToTelemetryClients()
throws Exception {
String trustStoreUrlPath = TestUtilities.getTestResourcePath("test_truststore_withpass.jks");
String url =
@@ -2106,16 +2104,21 @@ public void testConnectionPropagatesUniverseProxyAndTrustStoreToTelemetryClient(
.append("SSLTrustStorePwd", "testpassword")
.append("SSLTrustStoreType", "JKS")
.append("enableGcpTraceExporter", 1)
+ .append("enableGcpLogExporter", 1)
.append("EnableDiagnosticTelemetry", 0)
.toString();
OpenTelemetry mockOtel = mock(OpenTelemetry.class);
when(mockOtel.getTracer(anyString())).thenReturn(mock(Tracer.class));
+ GcpLogWriter mockLogWriter = mock(GcpLogWriter.class);
ArgumentCaptor traceConfigCaptor =
ArgumentCaptor.forClass(BigQueryJdbcOpenTelemetry.TelemetryTransportConfig.class);
+ ArgumentCaptor logConfigCaptor =
+ ArgumentCaptor.forClass(BigQueryJdbcOpenTelemetry.TelemetryTransportConfig.class);
try (MockedStatic mockedOtel =
- mockStatic(BigQueryJdbcOpenTelemetry.class)) {
+ mockStatic(BigQueryJdbcOpenTelemetry.class);
+ MockedStatic mockedLogWriter = mockStatic(GcpLogWriter.class)) {
mockedOtel
.when(
() ->
@@ -2129,35 +2132,71 @@ public void testConnectionPropagatesUniverseProxyAndTrustStoreToTelemetryClient(
any(),
traceConfigCaptor.capture()))
.thenReturn(mockOtel);
+ mockedLogWriter
+ .when(() -> GcpLogWriter.create(any(), any(), any(), any(), logConfigCaptor.capture()))
+ .thenReturn(mockLogWriter);
try (BigQueryConnection conn = new BigQueryConnection(url)) {
- // Connection initialization triggers getOpenTelemetry.
+ // Connection initialization triggers getOpenTelemetry and GcpLogWriter.create.
}
- BigQueryJdbcOpenTelemetry.TelemetryTransportConfig captured = traceConfigCaptor.getValue();
- assertEquals(CUSTOM_UNIVERSE, captured.universeDomain);
- assertEquals(
- "https://oauth2.custom.internal/token",
- captured.overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME));
- assertEquals(
- CUSTOM_UNIVERSE,
- captured.overrideProperties.get(
- BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
- assertEquals(
- "127.0.0.1",
- captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME));
- assertEquals(
- "3128", captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME));
- assertEquals(
- "proxy-user",
- captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME));
- assertEquals(
- "proxy-pass",
- captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME));
- assertEquals(trustStoreUrlPath, captured.sslTrustStorePath);
- assertEquals("testpassword", captured.sslTrustStorePassword);
- assertEquals("JKS", captured.sslTrustStoreType);
- assertNotNull(captured.httpTransportFactory);
+ for (BigQueryJdbcOpenTelemetry.TelemetryTransportConfig captured :
+ Arrays.asList(traceConfigCaptor.getValue(), logConfigCaptor.getValue())) {
+ assertEquals(CUSTOM_UNIVERSE, captured.universeDomain);
+ assertEquals(
+ "https://oauth2.custom.internal/token",
+ captured.overrideProperties.get(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME));
+ assertEquals(
+ CUSTOM_UNIVERSE,
+ captured.overrideProperties.get(
+ BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME));
+ assertEquals(
+ "127.0.0.1",
+ captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME));
+ assertEquals(
+ "3128", captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME));
+ assertEquals(
+ "proxy-user",
+ captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_USER_ID_PROPERTY_NAME));
+ assertEquals(
+ "proxy-pass",
+ captured.proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PASSWORD_PROPERTY_NAME));
+ assertEquals(trustStoreUrlPath, captured.sslTrustStorePath);
+ assertEquals("testpassword", captured.sslTrustStorePassword);
+ assertEquals("JKS", captured.sslTrustStoreType);
+ assertNotNull(captured.httpTransportFactory);
+ assertNotNull(captured.transportChannelProvider);
+ }
+ }
+ }
+
+ @Test
+ public void testConnectionReleasesOpenTelemetrySdkWhenLogWriterCreationFails() {
+ String url =
+ getUriOAuthServiceAccount()
+ .append("ProjectId", "telemetry-project")
+ .append("enableGcpLogExporter", 1)
+ .append("EnableDiagnosticTelemetry", 0)
+ .toString();
+
+ OpenTelemetry mockOtel = mock(OpenTelemetry.class);
+ try (MockedStatic mockedOtel =
+ mockStatic(BigQueryJdbcOpenTelemetry.class);
+ MockedStatic mockedLogWriter = mockStatic(GcpLogWriter.class)) {
+ mockedOtel
+ .when(
+ () ->
+ BigQueryJdbcOpenTelemetry.getOpenTelemetry(
+ anyBoolean(), anyBoolean(), anyBoolean(), any(), any(), any(), any(), any()))
+ .thenReturn(mockOtel);
+ mockedLogWriter
+ .when(() -> GcpLogWriter.create(any(), any(), any(), any(), any()))
+ .thenThrow(new BigQueryJdbcRuntimeException("log init failure"));
+
+ BigQueryJdbcRuntimeException ex =
+ assertThrows(BigQueryJdbcRuntimeException.class, () -> new BigQueryConnection(url));
+ assertTrue(ex.getMessage().contains("log init failure"));
+ mockedOtel.verify(() -> BigQueryJdbcOpenTelemetry.releaseSdk(mockOtel));
}
}
}
diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java
index df862a16af9e..b46b59e17d13 100644
--- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java
+++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcOpenTelemetryTest.java
@@ -18,6 +18,7 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
@@ -26,6 +27,10 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import com.google.api.MonitoredResource;
+import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
+import com.google.api.gax.rpc.FixedHeaderProvider;
+import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.auth.Credentials;
import com.google.auth.http.HttpTransportFactory;
import com.google.auth.oauth2.AccessToken;
@@ -36,9 +41,12 @@
import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
import com.google.cloud.bigquery.jdbc.BigQueryJdbcOpenTelemetry.TelemetryTransportConfig;
import com.google.cloud.bigquery.jdbc.utils.TestUtilities;
-import com.google.cloud.logging.Logging;
import com.google.common.io.ByteStreams;
import com.google.gson.JsonObject;
+import com.google.logging.type.LogSeverity;
+import com.google.logging.v2.LogEntry;
+import com.google.logging.v2.WriteLogEntriesRequest;
+import com.google.logging.v2.WriteLogEntriesResponse;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpsConfigurator;
import com.sun.net.httpserver.HttpsServer;
@@ -72,6 +80,8 @@
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
+import java.time.Instant;
+import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -104,6 +114,13 @@ public void tearDown() {
System.clearProperty("otel.exporter.otlp.compression");
}
+ private static MonitoredResource testMonitoredResource(String projectId) {
+ return MonitoredResource.newBuilder()
+ .setType("global")
+ .putLabels("project_id", projectId)
+ .build();
+ }
+
private static JsonObject buildServiceAccountJson(String email, String universeDomain) {
return BigQueryJdbcBaseTest.buildServiceAccountJson(email, "test-project", universeDomain);
}
@@ -135,6 +152,12 @@ private static Map proxyProperties(int port, String proxyUid, St
return props;
}
+ private static String basicAuthHeader(String user, String password) {
+ return "Basic "
+ + Base64.getEncoder()
+ .encodeToString((user + ":" + password).getBytes(StandardCharsets.UTF_8));
+ }
+
private static HttpsServer startLocalhostHttpsServer(
SSLContext serverSslContext, String path, HttpHandler handler) throws IOException {
HttpsServer server = HttpsServer.create(new InetSocketAddress("localhost", 0), 0);
@@ -393,26 +416,140 @@ public void testGetOpenTelemetry_withUseGlobalOTel_returnsGlobal() {
}
@Test
- public void testCreateLoggingClient_propagatesUniverseDomain() throws Exception {
+ public void testCreateGcpLogWriter_propagatesUniverseDomain() throws Exception {
GoogleCredentials customCreds =
GoogleCredentials.newBuilder()
.setAccessToken(new AccessToken("test-token", null))
.setUniverseDomain(CUSTOM_UNIVERSE)
.build();
- try (Logging logging =
- BigQueryJdbcOpenTelemetry.createLoggingClient(
- true, null, null, "test-project", customCreds, null, CUSTOM_UNIVERSE)) {
- assertThat(logging).isNotNull();
- assertThat(logging.getOptions().getUniverseDomain()).isEqualTo(CUSTOM_UNIVERSE);
+ TelemetryTransportConfig customConfig =
+ TelemetryTransportConfig.builder().setUniverseDomain(CUSTOM_UNIVERSE).build();
+ try (GcpLogWriter writer =
+ GcpLogWriter.create(
+ null,
+ "test-project",
+ customCreds,
+ null,
+ customConfig,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L)) {
+ assertThat(writer).isNotNull();
+ assertThat(writer.getLoggingClient().getSettings().getUniverseDomain())
+ .isEqualTo(CUSTOM_UNIVERSE);
}
GoogleCredentials defaultCreds =
GoogleCredentials.newBuilder().setAccessToken(new AccessToken("test-token", null)).build();
- try (Logging defaultLogging =
- BigQueryJdbcOpenTelemetry.createLoggingClient(
- true, null, null, "test-project", defaultCreds, null, null)) {
- assertThat(defaultLogging).isNotNull();
- assertThat(defaultLogging.getOptions().getUniverseDomain()).isNull();
+ try (GcpLogWriter defaultWriter =
+ GcpLogWriter.create(
+ null,
+ "test-project",
+ defaultCreds,
+ null,
+ EMPTY_TRANSPORT,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L)) {
+ assertThat(defaultWriter).isNotNull();
+ assertThat(defaultWriter.getLoggingClient().getSettings().getUniverseDomain())
+ .isEqualTo("googleapis.com");
+ }
+ }
+
+ @Test
+ public void testCreateGcpLogWriter_rejectsInvalidUniverseDomainAndMismatchedCredentials() {
+ TelemetryTransportConfig invalidUniverseConfig =
+ TelemetryTransportConfig.builder().setUniverseDomain("bad/host").build();
+ assertThrows(
+ BigQueryJdbcRuntimeException.class,
+ () ->
+ GcpLogWriter.create(
+ null,
+ "test-project",
+ null,
+ null,
+ invalidUniverseConfig,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L));
+
+ GoogleCredentials otherUniverseCreds =
+ GoogleCredentials.newBuilder()
+ .setAccessToken(new AccessToken("token", null))
+ .setUniverseDomain(OTHER_UNIVERSE)
+ .build();
+ TelemetryTransportConfig customUniverseConfig =
+ TelemetryTransportConfig.builder().setUniverseDomain(CUSTOM_UNIVERSE).build();
+ BigQueryJdbcRuntimeException mismatchEx =
+ assertThrows(
+ BigQueryJdbcRuntimeException.class,
+ () ->
+ GcpLogWriter.create(
+ null,
+ "test-project",
+ otherUniverseCreds,
+ null,
+ customUniverseConfig,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L));
+ assertThat(mismatchEx.getMessage()).contains(CUSTOM_UNIVERSE);
+ assertThat(mismatchEx.getMessage()).contains(OTHER_UNIVERSE);
+
+ // Omitted universeDomain defaults to googleapis.com and rejects custom-universe JSON creds.
+ String customSaJson =
+ buildServiceAccountJson("log@test.iam.gserviceaccount.com", CUSTOM_UNIVERSE).toString();
+ BigQueryJdbcRuntimeException omittedMismatch =
+ assertThrows(
+ BigQueryJdbcRuntimeException.class,
+ () ->
+ GcpLogWriter.create(
+ customSaJson,
+ "test-project",
+ null,
+ null,
+ EMPTY_TRANSPORT,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L));
+ assertThat(omittedMismatch.getMessage()).contains("googleapis.com");
+ assertThat(omittedMismatch.getMessage()).contains(CUSTOM_UNIVERSE);
+ }
+
+ @Test
+ public void testCreateGcpLogWriter_resolvesCredentialsStringWithOverridesAndTransportFactory()
+ throws Exception {
+ String customTokenUri = "https://oauth2.custom.internal/token";
+ Map overrides = new HashMap<>();
+ overrides.put(BigQueryJdbcUrlUtility.OAUTH2_TOKEN_URI_PROPERTY_NAME, customTokenUri);
+ HttpTransportFactory factory =
+ BigQueryJdbcProxyUtility.getHttpTransportOptions(
+ Collections.emptyMap(), null, null, null, null, null, null, "Test")
+ .getHttpTransportFactory();
+
+ String customSaJson =
+ buildServiceAccountJson("log@test.iam.gserviceaccount.com", CUSTOM_UNIVERSE).toString();
+ TelemetryTransportConfig config =
+ TelemetryTransportConfig.builder()
+ .setUniverseDomain(CUSTOM_UNIVERSE)
+ .setOverrideProperties(overrides)
+ .setHttpTransportFactory(factory)
+ .build();
+
+ try (GcpLogWriter writer =
+ GcpLogWriter.create(
+ customSaJson,
+ null,
+ null,
+ null,
+ config,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L)) {
+ assertThat(writer).isNotNull();
+ Credentials resolvedCreds =
+ writer.getLoggingClient().getSettings().getCredentialsProvider().getCredentials();
+ assertThat(resolvedCreds).isInstanceOf(ServiceAccountCredentials.class);
+ ServiceAccountCredentials sa = (ServiceAccountCredentials) resolvedCreds;
+ assertThat(sa.getUniverseDomain()).isEqualTo(CUSTOM_UNIVERSE);
+ assertThat(sa.getTokenServerUri()).isEqualTo(URI.create(customTokenUri));
+ assertThat(sa.getScopes()).contains(GcpLogWriter.LOGGING_WRITE_SCOPE);
+ assertThat(sa.toBuilder().getHttpTransportFactory()).isSameInstanceAs(factory);
}
}
@@ -583,7 +720,7 @@ public void testGetOpenTelemetry_skipsMetadataServerCallForComputeEngineCredenti
}
@Test
- public void testGetOpenTelemetry_skipsMetadataServerCallForImpersonatedComputeEngineCredentials()
+ public void testTelemetry_skipsMetadataServerCallForImpersonatedComputeEngineCredentials()
throws Exception {
ComputeEngineCredentials sourceGce = spy(ComputeEngineCredentials.create());
ImpersonatedCredentials impersonatedGce =
@@ -606,8 +743,17 @@ public void testGetOpenTelemetry_skipsMetadataServerCallForImpersonatedComputeEn
"impersonated-gce-proj",
impersonatedGce,
customUniverseConfig);
- try {
+ try (GcpLogWriter writer =
+ GcpLogWriter.create(
+ null,
+ "test-project",
+ impersonatedGce,
+ null,
+ customUniverseConfig,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 500L)) {
assertThat(otel).isInstanceOf(OpenTelemetrySdk.class);
+ assertThat(writer).isNotNull();
verify(sourceGce, never()).getUniverseDomain();
} finally {
BigQueryJdbcOpenTelemetry.releaseSdk(otel);
@@ -957,6 +1103,156 @@ public void testResolveCredentialsFromString_propagatesOverridesAndTransportFact
assertThat(saDefault.toBuilder().getHttpTransportFactory()).isSameInstanceAs(factory);
}
+ @Test
+ public void testCreateGcpLogWriter_usesConfiguredTransportChannelProvider() throws Exception {
+ AtomicInteger receivedWriteRequests = new AtomicInteger(0);
+ AtomicReference capturedRequest = new AtomicReference<>();
+ AtomicReference receivedGrpcAuthHeader = new AtomicReference<>();
+ AtomicReference receivedCustomHeader = new AtomicReference<>();
+ Metadata.Key authMetadataKey =
+ Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER);
+ Metadata.Key customMetadataKey =
+ Metadata.Key.of("x-driver-test", Metadata.ASCII_STRING_MARSHALLER);
+ ServerInterceptor headerCapturingInterceptor =
+ new ServerInterceptor() {
+ @Override
+ public ServerCall.Listener interceptCall(
+ ServerCall call, Metadata headers, ServerCallHandler next) {
+ receivedGrpcAuthHeader.set(headers.get(authMetadataKey));
+ receivedCustomHeader.set(headers.get(customMetadataKey));
+ return next.startCall(call, headers);
+ }
+ };
+
+ Server grpcServer =
+ startLocalhostTlsGrpcServer(
+ "google.logging.v2.LoggingServiceV2",
+ "google.logging.v2.LoggingServiceV2/WriteLogEntries",
+ bytes -> {
+ try {
+ return WriteLogEntriesRequest.parseFrom(bytes);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ },
+ WriteLogEntriesResponse::toByteArray,
+ request -> {
+ capturedRequest.set(request);
+ receivedWriteRequests.incrementAndGet();
+ return WriteLogEntriesResponse.getDefaultInstance();
+ },
+ headerCapturingInterceptor);
+
+ String expectedBasicAuth = basicAuthHeader("log-proxy-user", "log-proxy-pass");
+ AtomicInteger proxyAuthCount = new AtomicInteger(0);
+
+ try (ServerSocket proxyServer = new ServerSocket(0, 4, InetAddress.getLoopbackAddress())) {
+ startConnectProxyThread(proxyServer, expectedBasicAuth, grpcServer.getPort(), proxyAuthCount);
+
+ Map proxyProps =
+ proxyProperties(proxyServer.getLocalPort(), "log-proxy-user", "log-proxy-pass");
+ String trustStorePath = TestUtilities.getTestResourcePath("localhost-truststore.jks");
+ TransportChannelProvider baseProvider =
+ BigQueryJdbcProxyUtility.getTransportChannelProvider(
+ proxyProps, trustStorePath, "changeit", "JKS", null, "LoggingTest");
+ TransportChannelProvider localhostEndpointProvider =
+ ((InstantiatingGrpcChannelProvider) baseProvider)
+ .toBuilder().setEndpoint("localhost:" + grpcServer.getPort()).build();
+
+ GoogleCredentials creds =
+ GoogleCredentials.newBuilder()
+ .setAccessToken(new AccessToken("logging-token", null))
+ .setUniverseDomain(CUSTOM_UNIVERSE)
+ .build();
+ TelemetryTransportConfig transportConfig =
+ TelemetryTransportConfig.builder()
+ .setUniverseDomain(CUSTOM_UNIVERSE)
+ .setProxyProperties(proxyProps)
+ .setSslTrustStore(trustStorePath, "changeit", "JKS", null)
+ .setTransportChannelProvider(localhostEndpointProvider)
+ .build();
+
+ try (GcpLogWriter writer =
+ GcpLogWriter.create(
+ null,
+ "logging-project",
+ creds,
+ FixedHeaderProvider.create("x-driver-test", "header-ok"),
+ transportConfig,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 5_000L)) {
+ assertThat(writer.getLoggingClient().getSettings().getUniverseDomain())
+ .isEqualTo(CUSTOM_UNIVERSE);
+ writer.write(
+ "test-log",
+ LogSeverity.INFO,
+ Instant.ofEpochSecond(1700000000L, 123000000),
+ "test-log-message",
+ "0123456789abcdef0123456789abcdef",
+ "0123456789abcdef",
+ "conn-123");
+ writer.flush();
+ }
+
+ assertTrue(proxyAuthCount.get() >= 1, "Expected authenticated proxy tunnel for Logging gRPC");
+ assertEquals(1, receivedWriteRequests.get(), "Expected Logging RPC over configured channel");
+ assertEquals("Bearer logging-token", receivedGrpcAuthHeader.get());
+ assertEquals("header-ok", receivedCustomHeader.get());
+
+ WriteLogEntriesRequest sent = capturedRequest.get();
+ assertTrue(sent.getPartialSuccess());
+ assertEquals(1, sent.getEntriesCount());
+ LogEntry entry = sent.getEntries(0);
+ assertEquals("projects/logging-project/logs/test-log", entry.getLogName());
+ assertFalse(entry.getResource().getType().isEmpty());
+ assertEquals("logging-project", entry.getResource().getLabelsMap().get("project_id"));
+ assertEquals(LogSeverity.INFO, entry.getSeverity());
+ assertEquals("test-log-message", entry.getTextPayload());
+ assertEquals(
+ "projects/logging-project/traces/0123456789abcdef0123456789abcdef", entry.getTrace());
+ assertEquals("0123456789abcdef", entry.getSpanId());
+ assertEquals("conn-123", entry.getLabelsMap().get("jdbc.connection_id"));
+ } finally {
+ grpcServer.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testCreateGcpLogWriter_targetsUniverseDomainEndpointWithoutOverride()
+ throws Exception {
+ try (CapturingConnectProxy proxy = new CapturingConnectProxy()) {
+ Map proxyProps = proxyProperties(proxy.getPort(), null, null);
+ TransportChannelProvider provider =
+ BigQueryJdbcProxyUtility.getTransportChannelProvider(
+ proxyProps, null, null, null, null, "UniverseEndpointTest");
+ GoogleCredentials creds =
+ GoogleCredentials.newBuilder()
+ .setAccessToken(new AccessToken("logging-token", null))
+ .setUniverseDomain(CUSTOM_UNIVERSE)
+ .build();
+ TelemetryTransportConfig config =
+ TelemetryTransportConfig.builder()
+ .setUniverseDomain(CUSTOM_UNIVERSE)
+ .setProxyProperties(proxyProps)
+ .setTransportChannelProvider(provider)
+ .build();
+
+ try (GcpLogWriter writer =
+ GcpLogWriter.create(
+ null,
+ "logging-project",
+ creds,
+ null,
+ config,
+ BigQueryJdbcOpenTelemetryTest::testMonitoredResource,
+ 200L)) {
+ writer.write(
+ "test-log", LogSeverity.INFO, Instant.now(), "universe-check", null, null, "conn-u");
+ assertEquals("logging." + CUSTOM_UNIVERSE + ":443", proxy.awaitTarget());
+ }
+ }
+ }
+
private static void handleConnectTunnel(
Socket clientSocket, String expectedBasicAuth, int targetPort, AtomicInteger proxyAuthCount) {
Thread tunnelThread =
diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/GcpLogWriterTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/GcpLogWriterTest.java
new file mode 100644
index 000000000000..6adf06138ae6
--- /dev/null
+++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/GcpLogWriterTest.java
@@ -0,0 +1,366 @@
+/*
+ * Copyright 2026 Google LLC
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.google.cloud.bigquery.jdbc;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.google.api.MonitoredResource;
+import com.google.api.core.ApiFutures;
+import com.google.api.core.SettableApiFuture;
+import com.google.api.gax.rpc.TransportChannelProvider;
+import com.google.api.gax.rpc.UnaryCallable;
+import com.google.auth.oauth2.AccessToken;
+import com.google.auth.oauth2.GoogleCredentials;
+import com.google.auth.oauth2.ServiceAccountCredentials;
+import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
+import com.google.cloud.bigquery.jdbc.BigQueryJdbcOpenTelemetry.TelemetryTransportConfig;
+import com.google.cloud.logging.v2.LoggingClient;
+import com.google.logging.type.LogSeverity;
+import com.google.logging.v2.WriteLogEntriesRequest;
+import com.google.logging.v2.WriteLogEntriesResponse;
+import java.io.IOException;
+import java.time.Instant;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.logging.Level;
+import java.util.logging.LogRecord;
+import java.util.stream.Collectors;
+import org.junit.jupiter.api.Test;
+
+public class GcpLogWriterTest extends BigQueryJdbcLoggingBaseTest {
+
+ private static final MonitoredResource GLOBAL_RESOURCE = testResource("test-project");
+
+ private static MonitoredResource testResource(String projectId) {
+ return MonitoredResource.newBuilder()
+ .setType("global")
+ .putLabels("project_id", projectId)
+ .build();
+ }
+
+ @SuppressWarnings("unchecked")
+ private static UnaryCallable mockCallable() {
+ return mock(UnaryCallable.class);
+ }
+
+ @Test
+ public void testWriteAfterClose_isNoOp_andDoubleCloseIsIdempotent() {
+ LoggingClient client = mock(LoggingClient.class);
+ UnaryCallable callable = mockCallable();
+ when(client.writeLogEntriesCallable()).thenReturn(callable);
+ when(callable.futureCall(any()))
+ .thenReturn(ApiFutures.immediateFuture(WriteLogEntriesResponse.getDefaultInstance()));
+
+ GcpLogWriter writer = new GcpLogWriter(client, "test-project", GLOBAL_RESOURCE, 6_000L);
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "before-close", null, null, "conn-1");
+ writer.close();
+ writer.close();
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "after-close", null, null, "conn-1");
+
+ verify(callable, times(1)).futureCall(any());
+ verify(client, times(1)).close();
+ verify(client, never()).shutdownNow();
+ }
+
+ @Test
+ public void testWrite_guardsAgainstReentrantLogging() {
+ LoggingClient client = mock(LoggingClient.class);
+ UnaryCallable callable = mockCallable();
+ when(client.writeLogEntriesCallable()).thenReturn(callable);
+
+ AtomicReference writerRef = new AtomicReference<>();
+ AtomicInteger invocations = new AtomicInteger(0);
+ when(callable.futureCall(any()))
+ .thenAnswer(
+ invocation -> {
+ if (invocations.incrementAndGet() == 1) {
+ writerRef
+ .get()
+ .write("log-a", LogSeverity.INFO, Instant.now(), "nested", null, null, "c1");
+ }
+ return ApiFutures.immediateFuture(WriteLogEntriesResponse.getDefaultInstance());
+ });
+
+ GcpLogWriter writer = new GcpLogWriter(client, "test-project", GLOBAL_RESOURCE, 6_000L);
+ writerRef.set(writer);
+ try {
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "outer", null, null, "c1");
+ assertEquals(1, invocations.get(), "Re-entrant write must be skipped");
+ } finally {
+ writer.close();
+ }
+ }
+
+ @Test
+ public void testClose_callsShutdownNowWhenFlushTimesOut() {
+ LoggingClient client = mock(LoggingClient.class);
+ UnaryCallable callable = mockCallable();
+ when(client.writeLogEntriesCallable()).thenReturn(callable);
+ SettableApiFuture stalledFuture = SettableApiFuture.create();
+ when(callable.futureCall(any())).thenReturn(stalledFuture);
+
+ GcpLogWriter writer = new GcpLogWriter(client, "test-project", GLOBAL_RESOURCE, 50L);
+ writer.write("log-a", LogSeverity.WARNING, Instant.now(), "stalled", null, null, "conn-1");
+ writer.close();
+
+ verify(client, times(1)).shutdownNow();
+ verify(client, never()).close();
+ }
+
+ @Test
+ public void testFlush_restoresInterruptFlagAndCloseCallsShutdownNow() {
+ LoggingClient client = mock(LoggingClient.class);
+ UnaryCallable callable = mockCallable();
+ when(client.writeLogEntriesCallable()).thenReturn(callable);
+ SettableApiFuture stalledFuture = SettableApiFuture.create();
+ when(callable.futureCall(any())).thenReturn(stalledFuture);
+
+ GcpLogWriter writer = new GcpLogWriter(client, "test-project", GLOBAL_RESOURCE, 5_000L);
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "pending", null, null, "conn-1");
+
+ Thread.currentThread().interrupt();
+ try {
+ writer.flush();
+ assertTrue(Thread.currentThread().isInterrupted(), "flush() must restore interrupt flag");
+ } finally {
+ assertTrue(Thread.interrupted());
+ }
+
+ Thread.currentThread().interrupt();
+ try {
+ writer.close();
+ assertTrue(Thread.currentThread().isInterrupted(), "close() must restore interrupt flag");
+ } finally {
+ assertTrue(Thread.interrupted());
+ }
+ verify(client, times(1)).shutdownNow();
+ }
+
+ @Test
+ public void testConcurrentWriteAndClose_shutsDownStalledWriterAndSwallowsPostCloseRejection()
+ throws Exception {
+ LoggingClient client = mock(LoggingClient.class);
+ UnaryCallable callable = mockCallable();
+ when(client.writeLogEntriesCallable()).thenReturn(callable);
+
+ CountDownLatch insideFutureCall = new CountDownLatch(1);
+ CountDownLatch shutdownCalled = new CountDownLatch(1);
+ when(callable.futureCall(any()))
+ .thenAnswer(
+ invocation -> {
+ insideFutureCall.countDown();
+ assertTrue(shutdownCalled.await(5, TimeUnit.SECONDS));
+ throw new RejectedExecutionException("executor shut down during close");
+ });
+ doAnswer(
+ invocation -> {
+ shutdownCalled.countDown();
+ return null;
+ })
+ .when(client)
+ .shutdownNow();
+
+ GcpLogWriter writer = new GcpLogWriter(client, "test-project", GLOBAL_RESOURCE, 50L);
+ AtomicReference writerFailure = new AtomicReference<>();
+ Thread writerThread =
+ new Thread(
+ () -> {
+ try {
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "msg", null, null, "c1");
+ } catch (Throwable t) {
+ writerFailure.set(t);
+ }
+ });
+ writerThread.start();
+ assertTrue(insideFutureCall.await(5, TimeUnit.SECONDS));
+
+ writer.close();
+ writerThread.join(5_000L);
+ assertFalse(writerThread.isAlive());
+ assertThat(writerFailure.get()).isNull();
+ verify(client, times(1)).shutdownNow();
+ }
+
+ @Test
+ public void testResolveLoggingProjectId_precedenceAndMissingProject() {
+ String saJson =
+ BigQueryJdbcBaseTest.buildServiceAccountJson(
+ "sa@sa-project.iam.gserviceaccount.com", "sa-project", null)
+ .toString();
+ ServiceAccountCredentials sa =
+ (ServiceAccountCredentials)
+ BigQueryJdbcOpenTelemetry.resolveCredentialsFromString(saJson, null, null);
+
+ assertEquals(
+ "explicit-proj",
+ GcpLogWriter.resolveLoggingProjectId(" explicit-proj ", sa, () -> "default-proj"));
+ assertEquals(
+ "sa-project", GcpLogWriter.resolveLoggingProjectId(" ", sa, () -> "default-proj"));
+ assertEquals(
+ "default-proj", GcpLogWriter.resolveLoggingProjectId(null, null, () -> "default-proj"));
+
+ BigQueryJdbcRuntimeException ex =
+ assertThrows(
+ BigQueryJdbcRuntimeException.class,
+ () -> GcpLogWriter.resolveLoggingProjectId(null, null, () -> null));
+ assertThat(ex.getMessage()).contains("project ID");
+ }
+
+ @Test
+ public void testWriteFailure_logsFirstErrorOnceAndSummarizesDroppedCountOnClose() {
+ LoggingClient client = mock(LoggingClient.class);
+ UnaryCallable callable = mockCallable();
+ when(client.writeLogEntriesCallable()).thenReturn(callable);
+ when(callable.futureCall(any()))
+ .thenReturn(ApiFutures.immediateFailedFuture(new RuntimeException("PERMISSION_DENIED")));
+
+ GcpLogWriter writer = new GcpLogWriter(client, "test-project", GLOBAL_RESOURCE, 6_000L);
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "msg-1", null, null, "conn-1");
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "msg-2", null, null, "conn-1");
+ writer.write("log-a", LogSeverity.INFO, Instant.now(), "msg-3", null, null, "conn-1");
+
+ List warningsBeforeClose =
+ capturedLogs.stream()
+ .filter(r -> r.getLevel().intValue() >= Level.WARNING.intValue())
+ .map(LogRecord::getMessage)
+ .collect(Collectors.toList());
+ assertEquals(
+ 1, warningsBeforeClose.size(), "Only the first async failure should log a warning");
+ assertThat(warningsBeforeClose.get(0)).contains("PERMISSION_DENIED");
+
+ writer.close();
+ List warningsAfterClose =
+ capturedLogs.stream()
+ .filter(r -> r.getLevel().intValue() >= Level.WARNING.intValue())
+ .map(LogRecord::getMessage)
+ .collect(Collectors.toList());
+ assertEquals(2, warningsAfterClose.size(), "close() should summarize total dropped batches");
+ assertThat(warningsAfterClose.get(1)).contains("3");
+ }
+
+ @Test
+ public void testGetOrDetectMonitoredResource_cachesPerProjectId() {
+ GcpLogWriter.clearMonitoredResourceCacheForTest();
+ try {
+ AtomicInteger detections = new AtomicInteger(0);
+ MonitoredResource first =
+ GcpLogWriter.getOrDetectMonitoredResource(
+ "proj-a",
+ id -> {
+ detections.incrementAndGet();
+ return testResource(id);
+ });
+ MonitoredResource second =
+ GcpLogWriter.getOrDetectMonitoredResource(
+ "proj-a",
+ id -> {
+ detections.incrementAndGet();
+ return testResource(id);
+ });
+ MonitoredResource otherProject =
+ GcpLogWriter.getOrDetectMonitoredResource(
+ "proj-b",
+ id -> {
+ detections.incrementAndGet();
+ return testResource(id);
+ });
+
+ assertThat(first).isSameInstanceAs(second);
+ assertThat(first).isNotSameInstanceAs(otherProject);
+ assertEquals(2, detections.get());
+ } finally {
+ GcpLogWriter.clearMonitoredResourceCacheForTest();
+ }
+ }
+
+ @Test
+ public void testCreate_wrapsClientInitializationFailure() throws Exception {
+ TransportChannelProvider failingProvider = mock(TransportChannelProvider.class);
+ when(failingProvider.needsEndpoint()).thenReturn(false);
+ when(failingProvider.getTransportName()).thenReturn("grpc");
+ when(failingProvider.withUseS2A(anyBoolean())).thenReturn(failingProvider);
+ when(failingProvider.getTransportChannel()).thenThrow(new IOException("channel boom"));
+
+ TelemetryTransportConfig config =
+ TelemetryTransportConfig.builder().setTransportChannelProvider(failingProvider).build();
+
+ BigQueryJdbcRuntimeException ex =
+ assertThrows(
+ BigQueryJdbcRuntimeException.class,
+ () ->
+ GcpLogWriter.create(
+ null,
+ "test-project",
+ GoogleCredentials.newBuilder()
+ .setAccessToken(new AccessToken("tok", null))
+ .build(),
+ null,
+ config,
+ GcpLogWriterTest::testResource,
+ 500L));
+ assertThat(ex.getMessage()).contains("Failed to initialize Logging client");
+ assertThat(ex.getCause()).isInstanceOf(IOException.class);
+ assertThat(ex.getCause().getMessage()).contains("channel boom");
+ }
+
+ @Test
+ public void testCreate_preservesPreScopedServiceAccountCredentials() throws Exception {
+ String saJson =
+ BigQueryJdbcBaseTest.buildServiceAccountJson(
+ "sa@scoped-project.iam.gserviceaccount.com", "scoped-project", null)
+ .toString();
+ ServiceAccountCredentials preScoped =
+ (ServiceAccountCredentials)
+ ((ServiceAccountCredentials)
+ BigQueryJdbcOpenTelemetry.resolveCredentialsFromString(saJson, null, null))
+ .createScoped(
+ Collections.singletonList("https://www.googleapis.com/auth/bigquery"));
+
+ try (GcpLogWriter writer =
+ GcpLogWriter.create(
+ null,
+ "scoped-project",
+ preScoped,
+ null,
+ TelemetryTransportConfig.builder().build(),
+ GcpLogWriterTest::testResource,
+ 500L)) {
+ ServiceAccountCredentials actual =
+ (ServiceAccountCredentials)
+ writer.getLoggingClient().getSettings().getCredentialsProvider().getCredentials();
+ assertThat(actual.getScopes()).containsExactly("https://www.googleapis.com/auth/bigquery");
+ assertThat(writer.getResource().getLabelsMap()).containsEntry("project_id", "scoped-project");
+ }
+ }
+}
diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java
index bde45856b895..1ebe5d5c6ceb 100644
--- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java
+++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java
@@ -18,19 +18,20 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import com.google.cloud.logging.LogEntry;
-import com.google.cloud.logging.Logging;
-import com.google.cloud.logging.Payload;
+import com.google.logging.type.LogSeverity;
import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.logs.Severity;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.logs.data.LogRecordData;
import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension;
+import java.time.Instant;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogRecord;
@@ -39,7 +40,6 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
-import org.mockito.ArgumentCaptor;
public class OpenTelemetryJulHandlerTest {
@@ -114,31 +114,91 @@ public void testPublishWithFiltering() {
@Test
public void testPublishToGcp() {
- Logging loggingClient = mock(Logging.class);
+ GcpLogWriter logWriter = mock(GcpLogWriter.class);
BigQueryJdbcOpenTelemetry.registerConnection(
- "gcp-uuid", otelTesting.getOpenTelemetry(), loggingClient, true);
+ "gcp-uuid", otelTesting.getOpenTelemetry(), logWriter, true);
- BigQueryConnection mockConnection = mock(BigQueryConnection.class);
Baggage baggage =
Baggage.builder()
.put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, "gcp-uuid")
.build();
try (Scope scope = baggage.makeCurrent();
BigQueryJdbcMdc.MdcCloseable mdcScope = BigQueryJdbcMdc.registerInstance("gcp-uuid")) {
+ logger.severe("Severe msg");
+ logger.warning("Warning msg");
logger.info("Test message");
+ logger.config("Config msg");
+ logger.fine("Fine msg");
+ logger.finest("Finest msg");
logger.log(new LogRecord(Level.INFO, null));
}
- ArgumentCaptor> captor = ArgumentCaptor.forClass(Iterable.class);
- verify(loggingClient, times(2)).write(captor.capture());
-
- List> allWrites = captor.getAllValues();
- LogEntry entry = allWrites.get(0).iterator().next();
- LogEntry nullEntry = allWrites.get(1).iterator().next();
+ verify(logWriter)
+ .write(
+ eq("com.google.cloud.bigquery"),
+ eq(LogSeverity.ERROR),
+ any(Instant.class),
+ eq("Severe msg"),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
+ verify(logWriter)
+ .write(
+ eq("com.google.cloud.bigquery"),
+ eq(LogSeverity.WARNING),
+ any(Instant.class),
+ eq("Warning msg"),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
+ verify(logWriter)
+ .write(
+ eq("com.google.cloud.bigquery"),
+ eq(LogSeverity.INFO),
+ any(Instant.class),
+ eq("Test message"),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
+ verify(logWriter)
+ .write(
+ eq("com.google.cloud.bigquery"),
+ eq(LogSeverity.INFO),
+ any(Instant.class),
+ eq("Config msg"),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
+ verify(logWriter)
+ .write(
+ eq("com.google.cloud.bigquery"),
+ eq(LogSeverity.DEBUG),
+ any(Instant.class),
+ eq("Fine msg"),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
+ verify(logWriter)
+ .write(
+ eq("com.google.cloud.bigquery"),
+ eq(LogSeverity.DEBUG),
+ any(Instant.class),
+ eq("Finest msg"),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
+ verify(logWriter)
+ .write(
+ eq(BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME),
+ eq(LogSeverity.INFO),
+ any(Instant.class),
+ eq(""),
+ isNull(),
+ isNull(),
+ eq("gcp-uuid"));
- assertEquals("Test message", ((Payload.StringPayload) entry.getPayload()).getData());
- assertEquals(com.google.cloud.logging.Severity.INFO, entry.getSeverity());
- assertEquals("", ((Payload.StringPayload) nullEntry.getPayload()).getData());
+ new OpenTelemetryJulHandler().flush();
+ verify(logWriter).flush();
}
@Test