Skip to content
1 change: 1 addition & 0 deletions java-bigquery-jdbc/docs/USER_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,7 @@ Logging can also be configured globally across all driver connections using envi
| 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` |
| **`com.google.cloud.bigquery.jdbc.allowUrlLogPath`** | `true` | Controls whether `LogPath` supplied via JDBC URL / `Properties` (and implicit current-working-directory fallback) is honored. When `false`, only `BIGQUERY_JDBC_LOG_PATH` enables local log files. | `-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath=false` |

#### Log Level Reference:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME,
BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME,
BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME,
Expand Down Expand Up @@ -264,12 +263,29 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
private final AtomicReference<SessionState> sessionState =
new AtomicReference<>(new SessionState(null, Collections.emptyList(), false));

static String maskPropertyValue(String key, Object value) {
if (value == null) {
return null;
}
if (key == null || !SAFE_TO_LOG_PROPERTIES.contains(key)) {
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
return "*****";
}
return String.valueOf(value);
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
}

BigQueryConnection(String url) throws SQLException {
this(url, DataSource.fromUrl(url));
}

BigQueryConnection(String url, DataSource ds) throws SQLException {
this.connectionId = UUID.randomUUID().toString();
this(url, ds, UUID.randomUUID().toString());
}

BigQueryConnection(String url, DataSource ds, String connectionId) throws SQLException {
this.connectionId =
(connectionId != null && !connectionId.isEmpty())
? connectionId
: UUID.randomUUID().toString();
Baggage baggage =
Baggage.builder()
.put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, this.connectionId)
Expand All @@ -285,11 +301,7 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
Properties connectionProps = ds.createProperties();
Properties maskedProps = new Properties();
for (String name : connectionProps.stringPropertyNames()) {
String value = connectionProps.getProperty(name);
if (!SAFE_TO_LOG_PROPERTIES.contains(name)) {
value = "*****";
}
maskedProps.setProperty(name, value);
maskedProps.setProperty(name, maskPropertyValue(name, connectionProps.getProperty(name)));
}
LOG.config("Connection properties: %s", maskedProps.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

Expand Down Expand Up @@ -131,98 +132,133 @@ public Connection connect(String url, Properties info) throws SQLException {
AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED;
try {
if (acceptsURL(url)) {
Properties connectInfo = info == null ? new Properties() : (Properties) info.clone();
Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry");
String connectionId = UUID.randomUUID().toString();
BigQueryConnection connection = null;
boolean connectionReturned = false;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
try {
Properties connectInfo = info == null ? new Properties() : (Properties) info.clone();
Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry");

String connectionUri =
BigQueryJdbcUrlUtility.appendPropertiesToURL(
url.substring(5), this.toString(), connectInfo);
String connectionUri =
BigQueryJdbcUrlUtility.appendPropertiesToURL(
url.substring(5), this.toString(), connectInfo);

String telemetryOptOut =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME);
String telemetryOptOut =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri,
BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME);

if (telemetryOptOut != null) {
connectInfo.setProperty(
BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut);
}
TelemetryManager.getInstance(connectInfo);
if (telemetryOptOut != null) {
connectInfo.setProperty(
BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME,
telemetryOptOut);
}
TelemetryManager.getInstance(connectInfo);

Level logLevel;
String logPath;
try {
// LogLevel
String logLevelStr =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME);
if (logLevelStr == null) {
logLevelStr = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR);
}
logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr);
Level logLevel;
String logPath;
try {
// LogLevel
String logLevelStr =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.LOG_LEVEL_PROPERTY_NAME);
if (logLevelStr == null) {
logLevelStr = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR);
}
logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr);

// LogPath
logPath =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME);
if (logPath == null) {
logPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
}
// LogPath
String urlLogPath =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME);
String envLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
boolean allowUrlLogPath = BigQueryJdbcUrlUtility.isUrlLogPathAllowed();

// Fallback to default path only if not specified and not in Cloud-Only mode
String enableGcpLogExporterStr =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
boolean enableGcpLogExporter = false;
if (enableGcpLogExporterStr != null) {
enableGcpLogExporter =
BigQueryJdbcUrlUtility.convertToBoolean(
enableGcpLogExporterStr,
BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
}
if (logPath == null && !enableGcpLogExporter) {
logPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH;
}
String enableGcpLogExporterStr =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
boolean enableGcpLogExporter = false;
if (enableGcpLogExporterStr != null) {
enableGcpLogExporter =
BigQueryJdbcUrlUtility.convertToBoolean(
enableGcpLogExporterStr,
BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
}

BigQueryJdbcRootLogger.setLevel(logLevel, logPath);
} catch (RuntimeException e) {
LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e);
throw new BigQueryJdbcException("Failed to parse connection URL properties", e);
}
boolean ignoredUrlLogPath = false;
if (allowUrlLogPath) {
logPath = urlLogPath != null ? urlLogPath : envLogPath;
// Fallback to default path only if not specified and not in Cloud-Only mode
if (logPath == null && !enableGcpLogExporter) {
logPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH;
}
} else {
ignoredUrlLogPath = urlLogPath != null;
logPath = envLogPath;
}

// Logging starts from here.
DataSource ds;
try {
ds = DataSource.fromUrl(connectionUri);
} catch (BigQueryJdbcRuntimeException e) {
LOG.log(Level.SEVERE, "Failed to parse connection URL", e);
throw new BigQueryJdbcException("Failed to parse connection URL", e);
}
authType = TelemetryManager.toAuthenticationType(ds.getOAuthType());
if (customOpenTelemetryObj instanceof OpenTelemetry) {
ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj);
}
BigQueryConnection connection = new BigQueryConnection(connectionUri, ds);
DatabaseMetaData metaData = connection.getMetaData();
LOG.info(
"Driver info : { {Database Product Name : %s}, "
+ "{Database Product Version : %s}, "
+ "{Driver Name : %s}, "
+ "{Driver Version : %s}, "
+ "{LogLevel : %s}, "
+ "{LogPath : %s}, "
+ "{Driver Instance : %s} }",
metaData.getDatabaseProductName(),
metaData.getDatabaseProductVersion(),
metaData.getDriverName(),
metaData.getDriverVersion(),
logLevel,
logPath,
this.toString());
BigQueryJdbcRootLogger.setLevel(logLevel, logPath);
if (ignoredUrlLogPath) {
LOG.warning(
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
"Ignoring URL/Properties %s because system property %s is false.",
BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME,
BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY);
}
} catch (RuntimeException e) {
LOG.log(Level.SEVERE, "Failed to parse connection URL properties", e);
throw new BigQueryJdbcException("Failed to parse connection URL properties", e);
}

// Logging starts from here.
DataSource ds;
try {
ds = DataSource.fromUrl(connectionUri);
} catch (BigQueryJdbcRuntimeException e) {
LOG.log(Level.SEVERE, "Failed to parse connection URL", e);
throw new BigQueryJdbcException("Failed to parse connection URL", e);
}
authType = TelemetryManager.toAuthenticationType(ds.getOAuthType());
if (customOpenTelemetryObj instanceof OpenTelemetry) {
ds.setCustomOpenTelemetry((OpenTelemetry) customOpenTelemetryObj);
}
connection = new BigQueryConnection(connectionUri, ds, connectionId);
DatabaseMetaData metaData = connection.getMetaData();
LOG.info(
"Driver info : { {Database Product Name : %s}, "
+ "{Database Product Version : %s}, "
+ "{Driver Name : %s}, "
+ "{Driver Version : %s}, "
+ "{LogLevel : %s}, "
+ "{LogPath : %s}, "
+ "{Driver Instance : %s} }",
metaData.getDatabaseProductName(),
metaData.getDatabaseProductVersion(),
metaData.getDriverName(),
metaData.getDriverVersion(),
logLevel,
logPath,
this.toString());

Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class);
Connection wrapped = BigQueryJdbcContextProxy.wrap(connection, Connection.class);

TelemetryManager.recordConnectionAttempt(Status.STATUS_SUCCESS, 0, authType);
return wrapped;
TelemetryManager.recordConnectionAttempt(Status.STATUS_SUCCESS, 0, authType);
connectionReturned = true;
return wrapped;
} finally {
if (!connectionReturned) {
if (connection != null) {
try {
connection.close();
} catch (SQLException ignored) {
BigQueryJdbcRootLogger.closeConnectionHandler(connectionId);
}
} else {
BigQueryJdbcRootLogger.closeConnectionHandler(connectionId);
}
}
}
}
} else {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,23 @@ class BigQueryJdbcMdc {
private static final InheritableThreadLocal<String> currentConnectionId =
new InheritableThreadLocal<>();

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

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ public static synchronized void setLevel(Level level, String logPath) throws IOE
if (level != Level.OFF) {
if (logPath != null) {
setPath(logPath, level);
} else if (fileHandler != null) {
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
fileHandler.close();
logger.removeHandler(fileHandler);
fileHandler = null;
}
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
} else {
for (Handler h : logger.getHandlers()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ protected boolean removeEldestEntry(Map.Entry<String, Map<String, String>> eldes
static final String LOG_PATH_PROPERTY_NAME = "LogPath";
static final String LOG_LEVEL_ENV_VAR = "BIGQUERY_JDBC_LOG_LEVEL";
static final String LOG_PATH_ENV_VAR = "BIGQUERY_JDBC_LOG_PATH";
static final String ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY =
"com.google.cloud.bigquery.jdbc.allowUrlLogPath";
static final String ENABLE_SESSION_PROPERTY_NAME = "EnableSession";
static final String ENABLE_TIMESTAMP_PICOS_PROPERTY_NAME = "EnableTimestampPicos";
static final boolean DEFAULT_ENABLE_TIMESTAMP_PICOS_VALUE = false;
Expand Down Expand Up @@ -852,17 +854,33 @@ private static Map<String, String> parseUrlInternal(String url) {
* @param properties The properties to append.
* @return The string value of the updated URL.
*/
static boolean isUrlLogPathAllowed() {
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
String prop = System.getProperty(ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY);
return prop == null || !"false".equalsIgnoreCase(prop.trim());
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
}
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved

static String appendPropertiesToURL(String url, String callerClassName, Properties properties) {
LOG.finest("++enter++ " + callerClassName);
LOG.finest(() -> "++enter++ " + callerClassName);
if (properties == null || properties.isEmpty()) {
return url;
}
StringBuilder urlBuilder = new StringBuilder(url);
for (Entry<Object, Object> entry : properties.entrySet()) {
Comment thread
Neenu1995 marked this conversation as resolved.
Resolved
if (entry.getValue() != null && !"".equals(entry.getValue())) {
LOG.finest("Appending %s with value %s to URL", entry.getKey(), entry.getValue());
String encodedValue =
UrlEscapers.urlFormParameterEscaper()
.escape((String) entry.getValue())
.replace("+", "%20");
urlBuilder.append(";").append(entry.getKey()).append("=").append(encodedValue);
Object rawKey = entry.getKey();
Object rawValue = entry.getValue();
if (rawKey != null && rawValue != null) {
String key = String.valueOf(rawKey);
String valueStr = String.valueOf(rawValue);
if (!valueStr.isEmpty()) {
LOG.finest(
() ->
String.format(
"Appending %s with value %s to URL",
key, BigQueryConnection.maskPropertyValue(key, valueStr)));
String encodedValue =
UrlEscapers.urlFormParameterEscaper().escape(valueStr).replace("+", "%20");
urlBuilder.append(";").append(key).append("=").append(encodedValue);
}
}
}
return urlBuilder.toString();
Expand Down
Loading
Loading