-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathBigQueryJdbcRootLogger.java
More file actions
194 lines (168 loc) · 6.53 KB
/
Copy pathBigQueryJdbcRootLogger.java
File metadata and controls
194 lines (168 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/*
* Copyright 2023 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 com.google.common.base.Strings;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/** This class is used to log messages from the BigQuery JDBC Driver. */
class BigQueryJdbcRootLogger {
/**
* Note: Each connection will have its own file handler with the level and logPath specified in
* the connection properties. But the logs will be driver logs and not connection specific.
*/
private static final Logger logger = Logger.getLogger("com.google.cloud.bigquery");
private static final Logger storageLogger = Logger.getLogger("com.google.cloud.bigquery.storage");
private static final boolean isTest = Boolean.getBoolean("JDBC_TESTS");
private static Handler fileHandler = null;
static final String PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
private static final DateTimeFormatter DATE_FORMATTER =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS").withZone(ZoneId.systemDefault());
static String getThreadName(long threadId) {
Thread current = Thread.currentThread();
if (current.getId() == threadId) {
return current.getName();
}
ThreadGroup rootGroup = current.getThreadGroup();
while (rootGroup.getParent() != null) {
rootGroup = rootGroup.getParent();
}
int count = rootGroup.activeCount();
Thread[] threads = new Thread[count * 2];
int actualCount = rootGroup.enumerate(threads);
for (int i = 0; i < actualCount; i++) {
if (threads[i].getId() == threadId) {
return threads[i].getName();
}
}
return "";
}
static {
logger.setUseParentHandlers(false);
storageLogger.setUseParentHandlers(true);
if (isTest) {
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.SEVERE);
consoleHandler.setFormatter(getFormatter());
logger.addHandler(consoleHandler);
}
}
public static Formatter getFormatter() {
return new Formatter() {
private static final int MAX_THREAD_NAME_LENGTH = 15;
@Override
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];
}
}
String connStr =
(connectionId != null && !connectionId.isEmpty()) ? connectionId : "NO_CONN";
long threadId = record.getThreadID();
String threadName = getThreadName(threadId);
if (threadName.length() > MAX_THREAD_NAME_LENGTH) {
threadName = threadName.substring(threadName.length() - MAX_THREAD_NAME_LENGTH);
}
int totalPad = MAX_THREAD_NAME_LENGTH - threadName.length();
int leftPad = totalPad / 2;
String centeredThreadName =
Strings.repeat(" ", leftPad) + threadName + Strings.repeat(" ", totalPad - leftPad);
String sourceClassName =
record.getSourceClassName() != null
? record.getSourceClassName()
: record.getLoggerName();
String sourceMethodName = record.getSourceMethodName();
// Expected log format: yyyy-MM-dd HH:mm:ss.SSS [CONNECTION_ID] LEVEL PID --- [THREAD] CLASS
// METHOD: MESSAGE
StringBuilder sb = new StringBuilder(256);
sb.append(date)
.append(" [")
.append(connStr)
.append("] ")
.append(Strings.padEnd(record.getLevel().getName(), 7, ' '))
.append(" ")
.append(PROCESS_ID)
.append(" --- [")
.append(centeredThreadName)
.append("] ")
.append(Strings.padEnd(sourceClassName != null ? sourceClassName : "", 65, ' '))
.append(" ")
.append(Strings.padEnd(sourceMethodName != null ? sourceMethodName : "", 30, ' '))
.append(": ")
.append(record.getMessage())
.append(System.lineSeparator());
if (record.getThrown() != null) {
java.io.StringWriter sw = new java.io.StringWriter();
record.getThrown().printStackTrace(new java.io.PrintWriter(sw));
sb.append(sw.toString()).append(System.lineSeparator());
}
return sb.toString();
}
};
}
public static Logger getRootLogger() {
return logger;
}
public static void setLevel(Level level, String logPath) throws IOException {
if (level != Level.OFF) {
setPath(logPath, level);
logger.setLevel(level);
} else {
for (Handler h : logger.getHandlers()) {
h.close();
logger.removeHandler(h);
}
fileHandler = null;
}
}
static void setPath(String logPath, Level level) {
try {
if (logPath == null) {
logPath = "";
}
if (!logPath.isEmpty() && !logPath.endsWith("/")) {
logPath = logPath + "/";
}
if (fileHandler != null) {
fileHandler.close();
logger.removeHandler(fileHandler);
}
fileHandler = new PerConnectionFileHandler(logPath, level);
fileHandler.setLevel(level);
logger.addHandler(fileHandler);
logger.setUseParentHandlers(false);
} catch (Exception ex) {
logger.warning("Log File warning : " + ex);
}
}
public static void closeConnectionHandler(String connectionId) {
if (fileHandler instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) fileHandler).closeHandler(connectionId);
}
}
}