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 @@ -198,7 +198,7 @@ public Connection connect(String url, Properties info) throws SQLException {
logPath = envLogPath;
}

BigQueryJdbcRootLogger.setLevel(logLevel, logPath);
BigQueryJdbcRootLogger.registerConnection(connectionId, logLevel, logPath);
if (ignoredUrlLogPath) {
LOG.warning(
"Ignoring URL/Properties %s because system property %s is false.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,13 @@ class BigQueryJdbcRootLogger {
private static final ConcurrentHashMap<String, ConnectionLogContext> ACTIVE_CONNECTIONS =
new ConcurrentHashMap<>();

private static ConsoleHandler testConsoleHandler = null;
private static volatile PerConnectionFileHandler persistentFileHandler = null;
private static volatile Handler fileHandler = null;
private static volatile Level explicitGlobalLevel = Level.OFF;
private static Level lastDriverAppliedLevel = null;
private static boolean hasExternalFloor = false;
private static Level externalFloorLevel = null;

static final String PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];

Expand Down Expand Up @@ -82,6 +88,7 @@ static String getThreadName(long threadId) {
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.SEVERE);
consoleHandler.setFormatter(getFormatter());
testConsoleHandler = consoleHandler;
logger.addHandler(consoleHandler);
}
}
Expand Down Expand Up @@ -165,23 +172,145 @@ public static Logger getRootLogger() {
return logger;
}

public static synchronized void setLevel(Level level, String logPath) throws IOException {
if (level != Level.OFF) {
if (logPath != null) {
setPath(logPath, level);
} else if (fileHandler != null) {
fileHandler.close();
logger.removeHandler(fileHandler);
fileHandler = null;
private static synchronized PerConnectionFileHandler ensurePersistentFileHandlerAttached() {
if (persistentFileHandler == null || persistentFileHandler.isClosed()) {
persistentFileHandler = new PerConnectionFileHandler();
}
boolean attached = false;
for (Handler h : logger.getHandlers()) {
if (h == persistentFileHandler) {
attached = true;
break;
}
}
if (!attached) {
logger.addHandler(persistentFileHandler);
logger.setUseParentHandlers(false);
}
return persistentFileHandler;
}

private static boolean isDriverOwnedHandler(Handler handler) {
return handler instanceof PerConnectionFileHandler
|| handler instanceof OpenTelemetryJulHandler
|| (testConsoleHandler != null && handler == testConsoleHandler);
}

private static boolean hasExternalHandlerAttached() {
for (Handler h : logger.getHandlers()) {
if (!isDriverOwnedHandler(h)) {
return true;
}
}
return false;
}

static Level parseEnvLogLevel(String envLevelStr) {
if (envLevelStr == null || envLevelStr.trim().isEmpty() || "0".equals(envLevelStr.trim())) {
return Level.OFF;
}
return BigQueryJdbcUrlUtility.parseLogLevel(envLevelStr);
}

private static Level resolveInheritedLevel(Logger target) {
for (Logger p = target.getParent(); p != null; p = p.getParent()) {
Level pLevel = p.getLevel();
if (pLevel != null) {
return pLevel;
}
}
return Level.INFO;
}

private static synchronized void refreshEffectiveRootLevel() {
refreshEffectiveRootLevel(System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR));
}

static synchronized void refreshEffectiveRootLevel(String envLevelStr) {
Level current = logger.getLevel();
if (hasExternalHandlerAttached()) {
if (!hasExternalFloor || current != lastDriverAppliedLevel) {
hasExternalFloor = true;
externalFloorLevel = current;
}
} else {
for (Handler h : logger.getHandlers()) {
h.close();
logger.removeHandler(h);
hasExternalFloor = false;
externalFloorLevel = null;
}

int targetValue =
explicitGlobalLevel != null
? explicitGlobalLevel.intValue()
: ConnectionLogContext.OFF_VALUE;
if (envLevelStr != null) {
try {
targetValue = Math.min(targetValue, parseEnvLogLevel(envLevelStr).intValue());
} catch (RuntimeException ignored) {
// Invalid env level falls back to active connection levels.
}
}
for (ConnectionLogContext ctx : ACTIVE_CONNECTIONS.values()) {
targetValue = Math.min(targetValue, ctx.levelValue());
}
if (hasExternalFloor) {
if (externalFloorLevel != null) {
targetValue = Math.min(targetValue, externalFloorLevel.intValue());
} else {
Level inherited = resolveInheritedLevel(logger);
if (targetValue >= inherited.intValue()) {
lastDriverAppliedLevel = null;
logger.setLevel(null);
return;
}
}
}
Level applied =
(externalFloorLevel != null && targetValue == externalFloorLevel.intValue())
? externalFloorLevel
: toJulLevel(targetValue);
lastDriverAppliedLevel = applied;
logger.setLevel(applied);
}

private static Level toJulLevel(int levelValue) {
if (levelValue <= Level.ALL.intValue()) {
return Level.ALL;
}
if (levelValue <= Level.FINEST.intValue()) {
return Level.FINEST;
}
if (levelValue <= Level.FINER.intValue()) {
return Level.FINER;
}
if (levelValue <= Level.FINE.intValue()) {
return Level.FINE;
}
if (levelValue <= Level.CONFIG.intValue()) {
return Level.CONFIG;
}
if (levelValue <= Level.INFO.intValue()) {
return Level.INFO;
}
if (levelValue <= Level.WARNING.intValue()) {
return Level.WARNING;
}
if (levelValue <= Level.SEVERE.intValue()) {
return Level.SEVERE;
}
return Level.OFF;
}

public static synchronized void setLevel(Level level, String logPath) throws IOException {
Level effective = level != null ? level : Level.OFF;
explicitGlobalLevel = effective;
if (effective != Level.OFF && logPath != null) {
setPath(logPath, effective);
} else if (fileHandler != null) {
fileHandler.close();
logger.removeHandler(fileHandler);
fileHandler = null;
}
logger.setLevel(level);
refreshEffectiveRootLevel();
}

static synchronized void setPath(String logPath, Level level) {
Expand Down Expand Up @@ -212,16 +341,54 @@ static ConnectionLogContext registerConnection(String connectionId) {
if (connectionId == null || connectionId.isEmpty()) {
return null;
}
boolean[] created = {false};
ConnectionLogContext context =
ACTIVE_CONNECTIONS.computeIfAbsent(
connectionId, id -> new ConnectionLogContext(id, ConnectionLogContext.ALL_VALUE));
connectionId,
id -> {
created[0] = true;
return new ConnectionLogContext(id, ConnectionLogContext.OFF_VALUE);
});
Handler currentHandler = fileHandler;
if (currentHandler instanceof PerConnectionFileHandler) {
if (created[0] && currentHandler instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) currentHandler).registerConnection(connectionId);
}
return context;
}

static synchronized ConnectionLogContext registerConnection(
String connectionId, Level level, String logPath) throws IOException {
if (connectionId == null || connectionId.isEmpty()) {
return null;
}
Level effectiveLevel = level != null ? level : Level.OFF;
ConnectionLogContext context =
ACTIVE_CONNECTIONS.compute(
connectionId,
(id, existing) -> {
if (existing == null) {
return new ConnectionLogContext(id, effectiveLevel.intValue());
}
existing.setLevelValue(effectiveLevel.intValue());
return existing;
});
if (effectiveLevel != Level.OFF && logPath != null) {
try {
PerConnectionFileHandler persistent = ensurePersistentFileHandlerAttached();
boolean slotRegistered =
persistent.registerConnection(connectionId, effectiveLevel, logPath);
Handler legacy = fileHandler;
if (slotRegistered && legacy instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) legacy).registerConnection(connectionId);
}
} catch (Exception ex) {
logger.warning("Log File warning : " + ex);
}
Comment on lines +384 to +386

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

When catching an exception and logging it, avoid using string concatenation with the exception object (e.g., + ex) as it discards the stack trace and makes debugging difficult. Instead, pass the exception object as the third argument to logger.log to preserve the full stack trace.

Suggested change
} catch (Exception ex) {
logger.warning("Log File warning : " + ex);
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Log File warning", ex);
}

}
refreshEffectiveRootLevel();
return context;
}

static ConnectionLogContext findActiveContext(String connectionId) {
if (connectionId == null || connectionId.isEmpty()) {
return null;
Expand All @@ -245,9 +412,32 @@ public static synchronized void closeConnectionHandler(String connectionId) {
if (removed != null) {
removed.setLevelValue(ConnectionLogContext.OFF_VALUE);
}
if (persistentFileHandler != null) {
persistentFileHandler.closeHandler(connectionId);
}
Handler currentHandler = fileHandler;
if (currentHandler instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) currentHandler).closeHandler(connectionId);
}
refreshEffectiveRootLevel();
}

static synchronized void resetForTesting() {
for (String id : ACTIVE_CONNECTIONS.keySet()) {
ConnectionLogContext ctx = ACTIVE_CONNECTIONS.remove(id);
if (ctx != null) {
ctx.setLevelValue(ConnectionLogContext.OFF_VALUE);
}
if (persistentFileHandler != null) {
persistentFileHandler.closeHandler(id);
}
}
if (fileHandler != null) {
fileHandler.close();
logger.removeHandler(fileHandler);
fileHandler = null;
}
explicitGlobalLevel = Level.OFF;
refreshEffectiveRootLevel();
}
Comment on lines +425 to 442

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

To prevent state leakage and ensure test isolation, explicitly reset the static fields lastDriverAppliedLevel, hasExternalFloor, and externalFloorLevel to their default values in resetForTesting() before calling refreshEffectiveRootLevel().

  static synchronized void resetForTesting() {
    for (String id : ACTIVE_CONNECTIONS.keySet()) {
      ConnectionLogContext ctx = ACTIVE_CONNECTIONS.remove(id);
      if (ctx != null) {
        ctx.setLevelValue(ConnectionLogContext.OFF_VALUE);
      }
      if (persistentFileHandler != null) {
        persistentFileHandler.closeHandler(id);
      }
    }
    if (fileHandler != null) {
      fileHandler.close();
      logger.removeHandler(fileHandler);
      fileHandler = null;
    }
    explicitGlobalLevel = Level.OFF;
    lastDriverAppliedLevel = null;
    hasExternalFloor = false;
    externalFloorLevel = null;
    refreshEffectiveRootLevel();
  }

}
Loading
Loading