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 @@ -291,8 +291,8 @@ static String maskPropertyValue(String key, Object value) {
boolean initialized = false;
ExecutorService createdQueryExecutor = null;
ExecutorService createdMetadataExecutor = null;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) {
BigQueryJdbcRootLogger.registerConnection(this.connectionId);
try (BigQueryJdbcMdc.MdcCloseable mdc =
BigQueryJdbcMdc.registerAndBindConnection(this.connectionId)) {
this.connectionUrl = url;
if (LOG.isLoggable(Level.CONFIG)) {
Properties connectionProps = ds.createProperties();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ public Connection connect(String url, Properties info) throws SQLException {
String connectionId = UUID.randomUUID().toString();
BigQueryConnection connection = null;
boolean connectionReturned = false;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
try (BigQueryJdbcMdc.MdcCloseable mdc =
BigQueryJdbcMdc.registerAndBindConnection(connectionId)) {
Properties connectInfo = info == null ? new Properties() : (Properties) info.clone();
Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,13 @@ class BigQueryJdbcContextProxy implements InvocationHandler {

private final Object target;
private final String connectionId;
private final ConnectionLogContext connectionContext;
private final Class<?> interfaceType;

private BigQueryJdbcContextProxy(Object target, String connectionId, Class<?> interfaceType) {
this.target = target;
this.connectionId = connectionId;
this.connectionContext = BigQueryJdbcRootLogger.resolveContext(connectionId);
this.interfaceType = interfaceType;
}

Expand Down Expand Up @@ -132,7 +134,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
}

// Wrap execution in the context of the active connection for all non-bypassed methods
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerContext(connectionContext)) {
boolean isFinerLoggable = LOG.isLoggable(Level.FINER);
String targetClassName = null;
if (isFinerLoggable) {
Expand Down Expand Up @@ -173,7 +175,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl

// Unified Context Logger: Captures and logs every exception exactly once with the Connection
// context
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerContext(connectionContext)) {
String errMsg = cause.getMessage() != null ? cause.getMessage() : cause.toString();
LOG.severe("Exception occurred during " + methodName + ": " + errMsg, cause);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@
package com.google.cloud.bigquery.jdbc;

import java.util.function.Supplier;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class BigQueryJdbcCustomLogger extends Logger {
private volatile boolean hasOwnHandlers;

protected BigQueryJdbcCustomLogger(String name, String resourceBundleName) {
super(name, resourceBundleName);
Expand All @@ -32,6 +34,41 @@ public BigQueryJdbcCustomLogger(String name) {
this(name, null);
}

@Override
public synchronized void addHandler(Handler handler) throws SecurityException {
super.addHandler(handler);
this.hasOwnHandlers = getHandlers().length > 0;
}

@Override
public synchronized void removeHandler(Handler handler) throws SecurityException {
super.removeHandler(handler);
this.hasOwnHandlers = getHandlers().length > 0;
}

@Override
public boolean isLoggable(Level level) {
return isLoggableForContext(level, BigQueryJdbcMdc.getContext());
}

boolean isLoggableForContext(Level level, ConnectionLogContext ctx) {
if (level == null || !super.isLoggable(level)) {
return false;
}
if (this.hasOwnHandlers || BigQueryJdbcRootLogger.hasExternalHandler()) {
return true;
}
if (ctx != null) {
int rawThreshold = ctx.levelValue();
if (rawThreshold == ConnectionLogContext.INHERIT_VALUE) {
return true;
}
int threshold = Math.min(rawThreshold, BigQueryJdbcRootLogger.explicitGlobalLevelValue());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Update the call to use the renamed getter method getExplicitGlobalLevelValue() to maintain consistency and improve readability.

Suggested change
int threshold = Math.min(rawThreshold, BigQueryJdbcRootLogger.explicitGlobalLevelValue());
int threshold = Math.min(rawThreshold, BigQueryJdbcRootLogger.getExplicitGlobalLevelValue());

return threshold != ConnectionLogContext.OFF_VALUE && level.intValue() >= threshold;
}
return true;
}

private void logWithCaller(Level level, Supplier<String> msgSupplier) {
logWithCaller(level, null, msgSupplier);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,37 +33,60 @@ class BigQueryJdbcMdc {
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcMdc.class.getName());

private static final InheritableThreadLocal<String> currentConnectionId =
private static final InheritableThreadLocal<ConnectionLogContext> currentContext =
new InheritableThreadLocal<>();

/**
* Sets the current connection context on the executing thread and restores any enclosing context
* upon close.
* Binds the given {@link ConnectionLogContext} on the executing thread and restores any enclosing
* context upon close.
*/
static MdcCloseable registerInstance(String connectionId) {
if (connectionId == null) {
static MdcCloseable registerContext(ConnectionLogContext context) {
if (context == null) {
return () -> {};
}
String previous = currentConnectionId.get();
currentConnectionId.set(connectionId);
ConnectionLogContext previous = currentContext.get();
currentContext.set(context);
return () -> {
if (previous != null) {
currentConnectionId.set(previous);
currentContext.set(previous);
} else {
clear();
}
};
}

/**
* Sets the current connection context on the executing thread and restores any enclosing context
* upon close.
*/
static MdcCloseable registerInstance(String connectionId) {
if (connectionId == null) {
return () -> {};
}
return registerContext(BigQueryJdbcRootLogger.resolveContext(connectionId));
}

static MdcCloseable registerAndBindConnection(String connectionId) {
if (connectionId == null) {
return () -> {};
}
return registerContext(BigQueryJdbcRootLogger.registerConnection(connectionId));
}

static ConnectionLogContext getContext() {
return currentContext.get();
}

/**
* Returns the connection ID carried by any registered active connection on the current thread.
*/
static String getConnectionId() {
return currentConnectionId.get();
ConnectionLogContext ctx = currentContext.get();
return ctx != null ? ctx.connectionId() : null;
}

static void clear() {
currentConnectionId.remove();
currentContext.remove();
}

/**
Expand Down Expand Up @@ -190,40 +213,40 @@ public void execute(Runnable command) {

@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
return new MdcFutureTask<>(runnable, value, getConnectionId());
return new MdcFutureTask<>(runnable, value, getContext());
}

@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
return new MdcFutureTask<>(callable, getConnectionId());
return new MdcFutureTask<>(callable, getContext());
}

private static Runnable wrap(Runnable runnable) {
String connectionId = getConnectionId();
ConnectionLogContext context = getContext();
return () -> {
try (MdcCloseable mdc = registerInstance(connectionId)) {
try (MdcCloseable mdc = registerContext(context)) {
runnable.run();
}
};
}
}

private static class MdcFutureTask<V> extends FutureTask<V> {
private final String connectionId;
private final ConnectionLogContext context;

public MdcFutureTask(Runnable runnable, V result, String connectionId) {
MdcFutureTask(Runnable runnable, V result, ConnectionLogContext context) {
super(runnable, result);
this.connectionId = connectionId;
this.context = context;
}

public MdcFutureTask(Callable<V> callable, String connectionId) {
MdcFutureTask(Callable<V> callable, ConnectionLogContext context) {
super(callable);
this.connectionId = connectionId;
this.context = context;
}

@Override
public void run() {
try (MdcCloseable mdc = registerInstance(connectionId)) {
try (MdcCloseable mdc = registerContext(context)) {
super.run();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,7 @@ public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz, String conne
if (connectionId == null || connectionId.isEmpty()) {
return getLogger(clazz, (ConnectionLogContext) null);
}
ConnectionLogContext active = BigQueryJdbcRootLogger.findActiveContext(connectionId);
ConnectionLogContext context =
active != null
? active
: new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE);
return getLogger(clazz, context);
return getLogger(clazz, BigQueryJdbcRootLogger.resolveContext(connectionId));
}

static BigQueryJdbcResultSetLogger getLogger(
Expand All @@ -105,7 +100,12 @@ BigQueryJdbcCustomLogger delegate() {
}

public boolean isLoggable(Level level) {
return delegate.isLoggable(level);
if (level == null) {
return false;
}
ConnectionLogContext ctx =
connectionContext != null ? connectionContext : BigQueryJdbcMdc.getContext();
return delegate.isLoggableForContext(level, ctx);
}

public BigQueryJdbcResultSetLogger getArrowStructLogger() {
Expand Down Expand Up @@ -143,6 +143,9 @@ public BigQueryJdbcResultSetLogger getJsonArrayLogger() {
* BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily.
*/
public void log(LogRecord record) {
if (record == null || !isLoggable(record.getLevel())) {
return;
}
if (connectionContext != null) {
Object[] existingParams = record.getParameters();
if (existingParams == null || existingParams.length == 0) {
Expand All @@ -153,12 +156,20 @@ public void log(LogRecord record) {
System.arraycopy(existingParams, 0, newParams, 1, existingParams.length);
record.setParameters(newParams);
}
ConnectionLogContext threadContext = BigQueryJdbcMdc.getContext();
if (threadContext != null && threadContext != connectionContext) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

When threadContext is null but connectionContext is non-null, the MDC context is not registered before calling delegate.log(record). This means the log record will be dispatched with a null MDC context, which can cause routing or formatting issues if the downstream handlers or formatters rely on the MDC connection context.

We should simplify the condition to threadContext != connectionContext so that the context is also registered when the current thread has no active MDC context.

Suggested change
if (threadContext != null && threadContext != connectionContext) {
if (threadContext != connectionContext) {

try (BigQueryJdbcMdc.MdcCloseable ignored =
BigQueryJdbcMdc.registerContext(connectionContext)) {
delegate.log(record);
}
return;
}
}
delegate.log(record);
}

private void logTrace(Level level, String methodName, String msg) {
if (!delegate.isLoggable(level)) {
if (!isLoggable(level)) {
return;
}
LogRecord record = new LogRecord(level, msg);
Expand All @@ -168,15 +179,18 @@ private void logTrace(Level level, String methodName, String msg) {
}

private void logTrace(Level level, String methodName, Supplier<String> msgSupplier) {
if (!delegate.isLoggable(level)) {
if (!isLoggable(level)) {
return;
}
logTrace(level, methodName, msgSupplier.get());
LogRecord record = new LogRecord(level, msgSupplier.get());
record.setSourceClassName(targetClassName);
record.setSourceMethodName(methodName);
log(record);
}

/** Cold path: builds a record whose caller is inferred lazily by the formatter. */
private void logWithCaller(Level level, Throwable thrown, String msg) {
if (!delegate.isLoggable(level)) {
if (!isLoggable(level)) {
return;
}
LogRecord record = new BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord(level, msg);
Expand Down Expand Up @@ -244,7 +258,7 @@ public void fine(Supplier<String> msgSupplier) {
}

public void warning(String format, Object... args) {
if (!delegate.isLoggable(Level.WARNING)) {
if (!isLoggable(Level.WARNING)) {
return;
}
String message = (args == null || args.length == 0) ? format : String.format(format, args);
Expand Down
Loading
Loading