Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public final class BigQueryJdbcResultSetLogger {

private final BigQueryJdbcCustomLogger delegate;
private final String targetClassName;
private final ConnectionLogContext connectionContext;
private final String connectionId;

private volatile BigQueryJdbcResultSetLogger arrowStructLogger;
Expand All @@ -56,25 +57,36 @@ public final class BigQueryJdbcResultSetLogger {
private volatile BigQueryJdbcResultSetLogger jsonArrayLogger;

private BigQueryJdbcResultSetLogger(
BigQueryJdbcCustomLogger delegate, String targetClassName, String connectionId) {
BigQueryJdbcCustomLogger delegate,
String targetClassName,
ConnectionLogContext connectionContext) {
this.delegate = delegate;
this.targetClassName = targetClassName;
this.connectionId = connectionId;
this.connectionContext = connectionContext;
this.connectionId = connectionContext != null ? connectionContext.connectionId() : null;
}

public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz) {
return getLogger(clazz, null);
return getLogger(clazz, (ConnectionLogContext) null);
}

public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz, String connectionId) {
if (connectionId == null || connectionId.isEmpty()) {
return getLogger(clazz, (ConnectionLogContext) null);
}
return getLogger(clazz, new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE));
}

static BigQueryJdbcResultSetLogger getLogger(
Class<?> clazz, ConnectionLogContext connectionContext) {
String className = clazz.getName();
BigQueryJdbcCustomLogger delegate =
DELEGATES.computeIfAbsent(className, BigQueryJdbcCustomLogger::new);
if (connectionId == null) {
if (connectionContext == null) {
return GLOBAL_FACADES.computeIfAbsent(
className, k -> new BigQueryJdbcResultSetLogger(delegate, k, null));
}
return new BigQueryJdbcResultSetLogger(delegate, className, connectionId);
return new BigQueryJdbcResultSetLogger(delegate, className, connectionContext);
}

public String getConnectionId() {
Expand All @@ -92,46 +104,49 @@ public boolean isLoggable(Level level) {

public BigQueryJdbcResultSetLogger getArrowStructLogger() {
if (arrowStructLogger == null) {
arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionId);
arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionContext);
}
return arrowStructLogger;
}

public BigQueryJdbcResultSetLogger getJsonStructLogger() {
if (jsonStructLogger == null) {
jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionId);
jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionContext);
}
return jsonStructLogger;
}

public BigQueryJdbcResultSetLogger getArrowArrayLogger() {
if (arrowArrayLogger == null) {
arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionId);
arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionContext);
}
return arrowArrayLogger;
}

public BigQueryJdbcResultSetLogger getJsonArrayLogger() {
if (jsonArrayLogger == null) {
jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionId);
jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionContext);
}
return jsonArrayLogger;
}

/**
* Stamps the connection ID into {@code params[0]} and forwards to the shared logger. Does not
* touch the record's source class/method: hot-path callers set them explicitly, and cold-path
* callers ({@code severe}, {@code warning}) rely on {@link
* Stamps the {@link ConnectionLogContext} into {@code params[0]} and forwards to the shared
* logger. Does not touch the record's source class/method: hot-path callers set them explicitly,
* and cold-path callers ({@code severe}, {@code warning}) rely on {@link
* BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily.
*/
public void log(LogRecord record) {
if (connectionId != null) {
if (record == null) {
return;
}
if (connectionContext != null) {
Object[] existingParams = record.getParameters();
if (existingParams == null || existingParams.length == 0) {
record.setParameters(new Object[] {connectionId});
} else {
record.setParameters(new Object[] {connectionContext});
} else if (!(existingParams[0] instanceof ConnectionLogContext)) {
Object[] newParams = new Object[existingParams.length + 1];
newParams[0] = connectionId;
newParams[0] = connectionContext;
System.arraycopy(existingParams, 0, newParams, 1, existingParams.length);
record.setParameters(newParams);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@ public String format(LogRecord record) {
String date = DATE_FORMATTER.format(Instant.ofEpochMilli(record.getMillis()));
String connectionId = BigQueryJdbcMdc.getConnectionId();
if (connectionId == null || connectionId.isEmpty()) {
Object[] params = record.getParameters();
if (params != null && params.length > 0 && params[0] instanceof String) {
connectionId = (String) params[0];
ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record);
if (context != null) {
connectionId = context.connectionId();
}
}
String connStr =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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 java.util.Objects;
import java.util.logging.Level;
import java.util.logging.LogRecord;

/**
* Carries per-connection logging identity and threshold across threads and unproxied {@code
* ResultSet} log records without colliding with user or library {@code String} log parameters.
*/
final class ConnectionLogContext {
static final int OFF_VALUE = Level.OFF.intValue();
static final int ALL_VALUE = Level.ALL.intValue();

private final String connectionId;
private volatile int levelValue;

ConnectionLogContext(String connectionId, int levelValue) {
this.connectionId = Objects.requireNonNull(connectionId, "connectionId cannot be null");
this.levelValue = levelValue;
}

String connectionId() {
return connectionId;
}

int levelValue() {
return levelValue;
}

void setLevelValue(int levelValue) {
this.levelValue = levelValue;
}

static ConnectionLogContext extractFromParameters(LogRecord record) {
if (record == null) {
return null;
}
Object[] params = record.getParameters();
if (params != null && params.length > 0 && params[0] instanceof ConnectionLogContext) {
return (ConnectionLogContext) params[0];
}
return null;
}

@Override
public String toString() {
return connectionId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import io.opentelemetry.context.Context;
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;
Expand Down Expand Up @@ -63,6 +65,13 @@ public void publish(LogRecord record) {
connectionId = BigQueryJdbcMdc.getConnectionId();
}

if (connectionId == null || connectionId.isEmpty()) {
ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record);
if (context != null) {
connectionId = context.connectionId();
}
}

if (connectionId == null || connectionId.isEmpty()) {
return;
}
Expand Down Expand Up @@ -97,8 +106,9 @@ private void publishToGcp(LogRecord record, String connectionId, Logging logging
logId = UNSAFE_LOG_CHARACTERS.matcher(logId).replaceAll("_");
}

String formatted = formatMessage(record);
LogEntry.Builder builder =
LogEntry.newBuilder(Payload.StringPayload.of(formatMessage(record)))
LogEntry.newBuilder(Payload.StringPayload.of(formatted != null ? formatted : ""))
.setSeverity(mapGcpSeverity(record.getLevel()))
.setTimestamp(Instant.ofEpochMilli(record.getMillis()))
.setLogName(logId);
Expand Down Expand Up @@ -135,13 +145,16 @@ private void publishToOTel(LogRecord record, String connectionId, OpenTelemetry
? loggerName
: BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME);

String formatted = formatMessage(record);
LogRecordBuilder builder =
logger
.logRecordBuilder()
.setBody(formatMessage(record))
.setSeverity(mapSeverity(record.getLevel()))
.setTimestamp(Instant.ofEpochMilli(record.getMillis()))
.setContext(Context.current());
if (formatted != null) {
builder.setBody(formatted);
}

if (connectionId != null) {
builder.setAttribute(
Expand All @@ -165,15 +178,33 @@ private Severity mapSeverity(Level level) {

private String formatMessage(LogRecord record) {
String message = record.getMessage();
if (message == null) {
return null;
}
Object[] params = record.getParameters();
if (params != null && params.length > 0) {
try {
return java.text.MessageFormat.format(message, params);
} catch (IllegalArgumentException e) {
return message;
if (params == null || params.length == 0) {
return message;
}
int startIndex = (params[0] instanceof ConnectionLogContext) ? 1 : 0;
if (params.length <= startIndex || !hasPositionalPlaceholder(message)) {
return message;
}
Object[] messageParams =
startIndex == 0 ? params : Arrays.copyOfRange(params, startIndex, params.length);
try {
return MessageFormat.format(message, messageParams);
} catch (IllegalArgumentException e) {
return message;
}
}

private static boolean hasPositionalPlaceholder(String message) {
for (int i = 0; i <= 9; i++) {
if (message.indexOf("{" + i) >= 0) {
return true;
}
}
return message;
return false;
}
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -480,9 +480,9 @@ public void publish(LogRecord record) {

String connectionId = BigQueryJdbcMdc.getConnectionId();
if (connectionId == null || connectionId.isEmpty()) {
Object[] params = record.getParameters();
if (params != null && params.length > 0 && params[0] instanceof String) {
connectionId = (String) params[0];
ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record);
if (context != null) {
connectionId = context.connectionId();
}
}
boolean usedConnectionWriter = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,10 @@ public void testResultSetLoggerCachingBehavior() {
BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class);
BigQueryJdbcResultSetLogger globalLogger2 =
BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class);
BigQueryJdbcResultSetLogger emptyIdLogger =
BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, "");
assertSame(globalLogger1, globalLogger2);
assertSame(globalLogger1, emptyIdLogger);
// Connection-scoped facades are distinct lightweight objects, but they all forward to the
// single registered logger for the class — that is what prevents the registration leak.
BigQueryJdbcResultSetLogger connLogger1 =
Expand All @@ -360,14 +363,16 @@ public void testResultSetLoggerParameterPreservation() {
LogRecord record = new LogRecord(Level.INFO, "Processing job {0}");
record.setParameters(new Object[] {"job-999"});
rsLogger.log(record);
rsLogger.log(record);

List<LogRecord> records = rsHandler.getRecords();
assertEquals(1, records.size());
LogRecord loggedRecord = records.get(0);
assertEquals(2, records.size());
LogRecord loggedRecord = records.get(1);

Object[] params = loggedRecord.getParameters();
assertEquals(2, params.length);
assertEquals("conn-123", params[0]);
assertTrue(params[0] instanceof ConnectionLogContext);
assertEquals("conn-123", ((ConnectionLogContext) params[0]).connectionId());
assertEquals("job-999", params[1]);
} finally {
rsLogger.delegate().removeHandler(rsHandler);
Expand All @@ -394,7 +399,9 @@ private void assertConnectionIdPropagated(
capturedLogs.clear();
action.run();
assertEquals(1, capturedLogs.size());
assertEquals(connectionId, capturedLogs.get(0).getParameters()[0]);
Object firstParam = capturedLogs.get(0).getParameters()[0];
assertTrue(firstParam instanceof ConnectionLogContext);
assertEquals(connectionId, ((ConnectionLogContext) firstParam).connectionId());
assertTrue(assertLogContains(expectedMessage));
} finally {
BigQueryJdbcRootLogger.getRootLogger().setLevel(originalRootLevel);
Expand Down
Loading
Loading