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
10 changes: 10 additions & 0 deletions java-bigquery-jdbc/README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,16 @@ To configure these properties, you can use the following keys:
* Environment Variable: `BIGQUERY_JDBC_TELEMETRY_ENABLED=false`
* System Property: `-DBIGQUERY_JDBC_TELEMETRY_ENABLED=false`

## Diagnostic logging configuration

Diagnostic logging can be configured per connection via JDBC URL or connection properties (`LogLevel`, `LogPath`), globally via environment variables, or tuned at the JVM level via Java system properties:

* Environment Variables:
* `BIGQUERY_JDBC_LOG_LEVEL`: Default log verbosity level (`0` = `OFF` to `7` = `FINEST`, or `8` = `ALL`) when `LogLevel` is not specified on the connection.
* `BIGQUERY_JDBC_LOG_PATH`: Default directory path for driver log files when `LogPath` is not specified on the connection.
* Java System Properties:
* `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=<bytes>`: Maximum size in bytes of an active driver `.log` file before rotating onto a `.1.log` backup file (default: `1073741824`, or 1 GiB).

## Developer Guide

### Prerequisites
Expand Down
6 changes: 6 additions & 0 deletions java-bigquery-jdbc/docs/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,12 @@ Logging can also be configured globally across all driver connections using envi
| **`BIGQUERY_JDBC_LOG_LEVEL`** | `LogLevel` | Global default log verbosity level (`0`–`7` or `OFF`–`FINEST`). Overridden by `LogLevel` URL parameter. | `export BIGQUERY_JDBC_LOG_LEVEL=5` |
| **`BIGQUERY_JDBC_LOG_PATH`** | `LogPath` | Global output directory for driver log files. Overridden by `LogPath` URL parameter. | `export BIGQUERY_JDBC_LOG_PATH=/var/log/bigquery-jdbc` |

#### JVM System Properties for Logging:

| System Property | Default Value | Description | Example |
| :--- | :---: | :--- | :--- |
| **`com.google.cloud.bigquery.jdbc.maxLogFileBytes`** | `1073741824` (1 GiB) | Maximum size (in bytes) of an active `.log` file before rotating onto a `.1.log` backup file. | `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=536870912` |

#### Log Level Reference:

| Integer Value | String Constant | `java.util.logging` Level | Description |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@
* plus the connection ID of the ResultSet it serves.
*
* <p>Hot-path methods ({@code finestTrace} etc.) set the source class and method explicitly, so no
* stack-trace walking (caller inference) happens for them. The connection ID is stamped into {@code
* LogRecord.getParameters()[0]} on every record so {@code PerConnectionFileHandler} can route the
* record even when the thread-local MDC (mapped diagnostic context — the per-thread connection ID
* set by the JDBC proxy) is empty, which is the normal case for un-proxied ResultSet calls.
* stack-trace walking (caller inference) happens for them. A typed {@link ConnectionLogContext} is
* stamped into {@code LogRecord.getParameters()[0]} on every record so {@code
* PerConnectionFileHandler} can route the record even when the thread-local MDC (mapped diagnostic
* context — the per-thread connection ID set by the JDBC proxy) is empty, which is the normal case
* for un-proxied ResultSet calls.
*/
public final class BigQueryJdbcResultSetLogger {

Expand All @@ -49,32 +50,44 @@ public final class BigQueryJdbcResultSetLogger {
private final BigQueryJdbcCustomLogger delegate;
private final String targetClassName;
private final String connectionId;
private final ConnectionLogContext connectionContext;

private volatile BigQueryJdbcResultSetLogger arrowStructLogger;
private volatile BigQueryJdbcResultSetLogger jsonStructLogger;
private volatile BigQueryJdbcResultSetLogger arrowArrayLogger;
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 +105,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 formattedBody = formatMessage(record);
LogEntry.Builder builder =
LogEntry.newBuilder(Payload.StringPayload.of(formatMessage(record)))
LogEntry.newBuilder(Payload.StringPayload.of(formattedBody != null ? formattedBody : ""))
.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 formattedBody = formatMessage(record);
LogRecordBuilder builder =
logger
.logRecordBuilder()
.setBody(formatMessage(record))
.setSeverity(mapSeverity(record.getLevel()))
.setTimestamp(Instant.ofEpochMilli(record.getMillis()))
.setContext(Context.current());
if (formattedBody != null) {
builder.setBody(formattedBody);
}

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;
}

@Override
Expand Down
Loading
Loading