Skip to content

Commit 49fab70

Browse files
committed
fix(jdbc): replace String log parameter routing with typed ConnectionLogContext
1 parent e7799af commit 49fab70

8 files changed

Lines changed: 226 additions & 41 deletions

File tree

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java‎

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ public final class BigQueryJdbcResultSetLogger {
4848

4949
private final BigQueryJdbcCustomLogger delegate;
5050
private final String targetClassName;
51+
private final ConnectionLogContext connectionContext;
5152
private final String connectionId;
5253

5354
private volatile BigQueryJdbcResultSetLogger arrowStructLogger;
@@ -56,25 +57,36 @@ public final class BigQueryJdbcResultSetLogger {
5657
private volatile BigQueryJdbcResultSetLogger jsonArrayLogger;
5758

5859
private BigQueryJdbcResultSetLogger(
59-
BigQueryJdbcCustomLogger delegate, String targetClassName, String connectionId) {
60+
BigQueryJdbcCustomLogger delegate,
61+
String targetClassName,
62+
ConnectionLogContext connectionContext) {
6063
this.delegate = delegate;
6164
this.targetClassName = targetClassName;
62-
this.connectionId = connectionId;
65+
this.connectionContext = connectionContext;
66+
this.connectionId = connectionContext != null ? connectionContext.connectionId() : null;
6367
}
6468

6569
public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz) {
66-
return getLogger(clazz, null);
70+
return getLogger(clazz, (ConnectionLogContext) null);
6771
}
6872

6973
public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz, String connectionId) {
74+
if (connectionId == null || connectionId.isEmpty()) {
75+
return getLogger(clazz, (ConnectionLogContext) null);
76+
}
77+
return getLogger(clazz, new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE));
78+
}
79+
80+
static BigQueryJdbcResultSetLogger getLogger(
81+
Class<?> clazz, ConnectionLogContext connectionContext) {
7082
String className = clazz.getName();
7183
BigQueryJdbcCustomLogger delegate =
7284
DELEGATES.computeIfAbsent(className, BigQueryJdbcCustomLogger::new);
73-
if (connectionId == null) {
85+
if (connectionContext == null) {
7486
return GLOBAL_FACADES.computeIfAbsent(
7587
className, k -> new BigQueryJdbcResultSetLogger(delegate, k, null));
7688
}
77-
return new BigQueryJdbcResultSetLogger(delegate, className, connectionId);
89+
return new BigQueryJdbcResultSetLogger(delegate, className, connectionContext);
7890
}
7991

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

93105
public BigQueryJdbcResultSetLogger getArrowStructLogger() {
94106
if (arrowStructLogger == null) {
95-
arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionId);
107+
arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionContext);
96108
}
97109
return arrowStructLogger;
98110
}
99111

100112
public BigQueryJdbcResultSetLogger getJsonStructLogger() {
101113
if (jsonStructLogger == null) {
102-
jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionId);
114+
jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionContext);
103115
}
104116
return jsonStructLogger;
105117
}
106118

107119
public BigQueryJdbcResultSetLogger getArrowArrayLogger() {
108120
if (arrowArrayLogger == null) {
109-
arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionId);
121+
arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionContext);
110122
}
111123
return arrowArrayLogger;
112124
}
113125

114126
public BigQueryJdbcResultSetLogger getJsonArrayLogger() {
115127
if (jsonArrayLogger == null) {
116-
jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionId);
128+
jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionContext);
117129
}
118130
return jsonArrayLogger;
119131
}
120132

121133
/**
122-
* Stamps the connection ID into {@code params[0]} and forwards to the shared logger. Does not
123-
* touch the record's source class/method: hot-path callers set them explicitly, and cold-path
124-
* callers ({@code severe}, {@code warning}) rely on {@link
134+
* Stamps the {@link ConnectionLogContext} into {@code params[0]} and forwards to the shared
135+
* logger. Does not touch the record's source class/method: hot-path callers set them explicitly,
136+
* and cold-path callers ({@code severe}, {@code warning}) rely on {@link
125137
* BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily.
126138
*/
127139
public void log(LogRecord record) {
128-
if (connectionId != null) {
140+
if (record == null) {
141+
return;
142+
}
143+
if (connectionContext != null) {
129144
Object[] existingParams = record.getParameters();
130145
if (existingParams == null || existingParams.length == 0) {
131-
record.setParameters(new Object[] {connectionId});
132-
} else {
146+
record.setParameters(new Object[] {connectionContext});
147+
} else if (!(existingParams[0] instanceof ConnectionLogContext)) {
133148
Object[] newParams = new Object[existingParams.length + 1];
134-
newParams[0] = connectionId;
149+
newParams[0] = connectionContext;
135150
System.arraycopy(existingParams, 0, newParams, 1, existingParams.length);
136151
record.setParameters(newParams);
137152
}

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,9 @@ public String format(LogRecord record) {
104104
String date = DATE_FORMATTER.format(Instant.ofEpochMilli(record.getMillis()));
105105
String connectionId = BigQueryJdbcMdc.getConnectionId();
106106
if (connectionId == null || connectionId.isEmpty()) {
107-
Object[] params = record.getParameters();
108-
if (params != null && params.length > 0 && params[0] instanceof String) {
109-
connectionId = (String) params[0];
107+
ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record);
108+
if (context != null) {
109+
connectionId = context.connectionId();
110110
}
111111
}
112112
String connStr =
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright 2026 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.google.cloud.bigquery.jdbc;
18+
19+
import java.util.Objects;
20+
import java.util.logging.Level;
21+
import java.util.logging.LogRecord;
22+
23+
/**
24+
* Carries per-connection logging identity and threshold across threads and unproxied {@code
25+
* ResultSet} log records without colliding with user or library {@code String} log parameters.
26+
*/
27+
final class ConnectionLogContext {
28+
static final int OFF_VALUE = Level.OFF.intValue();
29+
static final int ALL_VALUE = Level.ALL.intValue();
30+
31+
private final String connectionId;
32+
private volatile int levelValue;
33+
34+
ConnectionLogContext(String connectionId, int levelValue) {
35+
this.connectionId = Objects.requireNonNull(connectionId, "connectionId cannot be null");
36+
this.levelValue = levelValue;
37+
}
38+
39+
String connectionId() {
40+
return connectionId;
41+
}
42+
43+
int levelValue() {
44+
return levelValue;
45+
}
46+
47+
void setLevelValue(int levelValue) {
48+
this.levelValue = levelValue;
49+
}
50+
51+
static ConnectionLogContext extractFromParameters(LogRecord record) {
52+
if (record == null) {
53+
return null;
54+
}
55+
Object[] params = record.getParameters();
56+
if (params != null && params.length > 0 && params[0] instanceof ConnectionLogContext) {
57+
return (ConnectionLogContext) params[0];
58+
}
59+
return null;
60+
}
61+
62+
@Override
63+
public String toString() {
64+
return connectionId;
65+
}
66+
}

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@
2828
import io.opentelemetry.api.trace.Span;
2929
import io.opentelemetry.api.trace.SpanContext;
3030
import io.opentelemetry.context.Context;
31+
import java.text.MessageFormat;
3132
import java.time.Instant;
33+
import java.util.Arrays;
3234
import java.util.Collections;
3335
import java.util.logging.ErrorManager;
3436
import java.util.logging.Handler;
@@ -63,6 +65,13 @@ public void publish(LogRecord record) {
6365
connectionId = BigQueryJdbcMdc.getConnectionId();
6466
}
6567

68+
if (connectionId == null || connectionId.isEmpty()) {
69+
ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record);
70+
if (context != null) {
71+
connectionId = context.connectionId();
72+
}
73+
}
74+
6675
if (connectionId == null || connectionId.isEmpty()) {
6776
return;
6877
}
@@ -97,8 +106,9 @@ private void publishToGcp(LogRecord record, String connectionId, Logging logging
97106
logId = UNSAFE_LOG_CHARACTERS.matcher(logId).replaceAll("_");
98107
}
99108

109+
String formatted = formatMessage(record);
100110
LogEntry.Builder builder =
101-
LogEntry.newBuilder(Payload.StringPayload.of(formatMessage(record)))
111+
LogEntry.newBuilder(Payload.StringPayload.of(formatted != null ? formatted : ""))
102112
.setSeverity(mapGcpSeverity(record.getLevel()))
103113
.setTimestamp(Instant.ofEpochMilli(record.getMillis()))
104114
.setLogName(logId);
@@ -135,13 +145,16 @@ private void publishToOTel(LogRecord record, String connectionId, OpenTelemetry
135145
? loggerName
136146
: BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME);
137147

148+
String formatted = formatMessage(record);
138149
LogRecordBuilder builder =
139150
logger
140151
.logRecordBuilder()
141-
.setBody(formatMessage(record))
142152
.setSeverity(mapSeverity(record.getLevel()))
143153
.setTimestamp(Instant.ofEpochMilli(record.getMillis()))
144154
.setContext(Context.current());
155+
if (formatted != null) {
156+
builder.setBody(formatted);
157+
}
145158

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

166179
private String formatMessage(LogRecord record) {
167180
String message = record.getMessage();
181+
if (message == null) {
182+
return null;
183+
}
168184
Object[] params = record.getParameters();
169-
if (params != null && params.length > 0) {
170-
try {
171-
return java.text.MessageFormat.format(message, params);
172-
} catch (IllegalArgumentException e) {
173-
return message;
185+
if (params == null || params.length == 0) {
186+
return message;
187+
}
188+
int startIndex = (params[0] instanceof ConnectionLogContext) ? 1 : 0;
189+
if (params.length <= startIndex || !hasPositionalPlaceholder(message)) {
190+
return message;
191+
}
192+
Object[] messageParams =
193+
startIndex == 0 ? params : Arrays.copyOfRange(params, startIndex, params.length);
194+
try {
195+
return MessageFormat.format(message, messageParams);
196+
} catch (IllegalArgumentException e) {
197+
return message;
198+
}
199+
}
200+
201+
private static boolean hasPositionalPlaceholder(String message) {
202+
for (int i = 0; i <= 9; i++) {
203+
if (message.indexOf("{" + i) >= 0) {
204+
return true;
174205
}
175206
}
176-
return message;
207+
return false;
177208
}
178209

179210
@Override

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -486,9 +486,9 @@ public void publish(LogRecord record) {
486486

487487
String connectionId = BigQueryJdbcMdc.getConnectionId();
488488
if (connectionId == null || connectionId.isEmpty()) {
489-
Object[] params = record.getParameters();
490-
if (params != null && params.length > 0 && params[0] instanceof String) {
491-
connectionId = (String) params[0];
489+
ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record);
490+
if (context != null) {
491+
connectionId = context.connectionId();
492492
}
493493
}
494494
ChannelLogWriter target = defaultWriter;

‎java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,10 @@ public void testResultSetLoggerCachingBehavior() {
335335
BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class);
336336
BigQueryJdbcResultSetLogger globalLogger2 =
337337
BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class);
338+
BigQueryJdbcResultSetLogger emptyIdLogger =
339+
BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, "");
338340
assertSame(globalLogger1, globalLogger2);
341+
assertSame(globalLogger1, emptyIdLogger);
339342
// Connection-scoped facades are distinct lightweight objects, but they all forward to the
340343
// single registered logger for the class — that is what prevents the registration leak.
341344
BigQueryJdbcResultSetLogger connLogger1 =
@@ -360,14 +363,16 @@ public void testResultSetLoggerParameterPreservation() {
360363
LogRecord record = new LogRecord(Level.INFO, "Processing job {0}");
361364
record.setParameters(new Object[] {"job-999"});
362365
rsLogger.log(record);
366+
rsLogger.log(record);
363367

364368
List<LogRecord> records = rsHandler.getRecords();
365-
assertEquals(1, records.size());
366-
LogRecord loggedRecord = records.get(0);
369+
assertEquals(2, records.size());
370+
LogRecord loggedRecord = records.get(1);
367371

368372
Object[] params = loggedRecord.getParameters();
369373
assertEquals(2, params.length);
370-
assertEquals("conn-123", params[0]);
374+
assertTrue(params[0] instanceof ConnectionLogContext);
375+
assertEquals("conn-123", ((ConnectionLogContext) params[0]).connectionId());
371376
assertEquals("job-999", params[1]);
372377
} finally {
373378
rsLogger.delegate().removeHandler(rsHandler);
@@ -394,7 +399,9 @@ private void assertConnectionIdPropagated(
394399
capturedLogs.clear();
395400
action.run();
396401
assertEquals(1, capturedLogs.size());
397-
assertEquals(connectionId, capturedLogs.get(0).getParameters()[0]);
402+
Object firstParam = capturedLogs.get(0).getParameters()[0];
403+
assertTrue(firstParam instanceof ConnectionLogContext);
404+
assertEquals(connectionId, ((ConnectionLogContext) firstParam).connectionId());
398405
assertTrue(assertLogContains(expectedMessage));
399406
} finally {
400407
BigQueryJdbcRootLogger.getRootLogger().setLevel(originalRootLevel);

0 commit comments

Comments
 (0)