Elffuss BraidHub

kikocis/java-driver public

a35fec42e322 · 11.6 KiBRenderedRawPermalink
1## Logging
2
3### Setup
4
5DataStax Java driver uses the popular [SLF4J](http://www.slf4j.org) library to emit log messages;
6SLF4J has the advantage of providing a logging API that is entirely decoupled from concrete
7implementations, letting client applications free to seamlessly connect SLF4J to their preferred logging backend.
8
9The driver itself does not attempt to configure any concrete logging framework.
10It is up to client applications using the driver to correctly set up their classpath and
11runtime configuration to be able to capture log messages emitted by the driver.
12Concretely, client applications need to provide, at runtime, a *binding* to any logging framework
13of their choice that is [compatible with SLF4J](http://www.slf4j.org/manual.html#swapping).
14
15If your application is built with Maven, this usually involves adding one (runtime) dependency to your POM file.
16For example, if you intend to use [Logback](http://logback.qos.ch), add the following dependency:
17
18```xml
19<dependency>
20 <groupId>ch.qos.logback</groupId>
21 <artifactId>logback-classic</artifactId>
22 <version>1.1.3</version>
23</dependency>
24```
25
26If you are using Log4J 1.2 instead, add the following dependency:
27
28```xml
29<dependency>
30 <groupId>org.slf4j</groupId>
31 <artifactId>slf4j-log4j12</artifactId>
32 <version>1.7.12</version>
33</dependency>
34```
35
36Check [SLF4J's documentation](http://www.slf4j.org/manual.html#projectDep) for examples for
37other logging frameworks, and for troubleshooting dependency resolution problems.
38
39### Configuration
40
41Each logging framework has its own configuration rules, but all of them provide
42different levels (DEBUG, INFO, WARN, ERROR...), different *loggers* or *categories*
43(messages from different categories or loggers can be filtered out separately or printed out
44differently), and different *appenders* (message receptacles such as the standard console,
45the error console, a file on disk, a socket...).
46
47Check your logging framework documentation for more information about how to properly configure it.
48You can also find some configuration examples below.
49
50### Useful loggers
51
52When debugging the Java driver, the following loggers could be particularly useful
53and provide hints about what's going wrong.
54
55* `com.datastax.driver.core.Cluster`
56 * ERROR
57 * Authentication errors
58 * Unexpected errors when handling events, reconnecting, refreshing schemas
59 * Unexpected events
60 * WARN
61 * Cluster name mismatches
62 * Unreachable contact points
63 * Unsupported protocol versions
64 * Schema disagreements
65 * Ignored notifications due to high contention
66 * INFO
67 * Hosts added or removed
68 * DEBUG
69 * Cluster lifecycle (start, shutdown)
70 * Event delivery notifications (schema changes, topology changes)
71 * Topology change events: hosts Up / Down / Added / Removed
72 * Hosts being ignored
73 * Protocol version negotiation
74 * Reconnection attempts
75 * Schema metadata refreshes
76 * TRACE
77 * Connection pools lifecycle (create, renew, refresh)
78* `com.datastax.driver.core.Session`
79 * ERROR
80 * Errors related to connection pools
81 * WARN
82 * Problems related to connection pools
83 * DEBUG
84 * Connection pools lifecycle (create, renew, refresh)
85* `com.datastax.driver.core.RequestHandler`
86 * ERROR
87 * Unexpected errors preparing queries
88 * Queries sent to a bootstrapping host
89 * Unexpected server errors
90 * WARN
91 * Queries sent to an overloaded host
92 * INFO
93 * Unprepared queries
94 * DEBUG
95 * Retry attempts
96 * TRACE
97 * Host currently being queried
98* `com.datastax.driver.core.Connection`
99 * WARN
100 * Problem setting keyspace
101 * Errors closing Netty channel
102 * DEBUG
103 * Connection lifecycle (open, close, defunct)
104 * Error connecting or writing requests
105 * Heartbeats
106 * TRACE
107 * Authentication progress
108 * Sending requests
109 * Receiving responses
110
111### Logging query latencies
112
113The `QueryLogger` provides clients with the ability to log queries
114executed by the driver, and especially, it allows client to track slow
115queries, i.e. queries that take longer to complete than a configured
116threshold in milliseconds.
117
118To turn on this feature, you first need to instantiate and register a `QueryLogger` instance:
119
120```java
121Cluster cluster = ...
122QueryLogger queryLogger = QueryLogger.builder(cluster)
123 .withConstantThreshold(...)
124 .withMaxQueryStringLength(...)
125.build();
126cluster.register(queryLogger);
127```
128
129Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide.
130Besides, you can adjust several parameters such as the maximum query string length to be printed,
131the maximum number of parameters to print, etc. Refer to the
132`QueryLogger` [API docs][query_logger] for more information.
133
134Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger`
135uses 3 different loggers:
136
137* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds.
138* `com.datastax.driver.core.QueryLogger.SLOW` : Used to log slow queries, i.e., queries that completed successfully but that took longer than a configurable threshold in milliseconds to complete.
139* `com.datastax.driver.core.QueryLogger.ERROR`: Used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. Note this this logger will also print the full stack trace of the reported exception.
140
141You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries
142that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above),
143then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J:
144
145```xml
146 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
147 <level value="DEBUG"/>
148 </logger>
149```
150
151The `QueryLogger` would then print messages such as this for every slow query:
152
153```
154DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?;
155```
156
157As you can see, actual query parameters are not logged; if you want them to be printed as well, set the `com.datastax.driver.core.QueryLogger.SLOW` logger
158to TRACE instead, e.g. with Log4J:
159
160```xml
161 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
162 <level value="TRACE"/>
163 </logger>
164```
165
166The `QueryLogger` would then print messages such as this for every slow query:
167
168```
169TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42];
170```
171
172Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters.
173See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary.
174
175#### Constant vs Dynamic thresholds
176
177Currently the `QueryLogger` can be configured to track slow queries using either
178a constant threshold in milliseconds (which is the default behavior), or
179a dynamic threshold based on latency percentiles, as computed by a `PercentileTracker` (see the
180[speculative executions](../speculative_execution/#percentile-speculative-execution-policy) section for more information
181about percentile trackers).
182
183Refer to the `QueryLogger` [API docs][query_logger] for an example of usage.
184
185### Performance Tips
186
187* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html)
188and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders
189that can significantly boost latencies when writing log messages.
190* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration
191without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html);
192Log4J provides a `configureAndWatch()` method but it is not recommended to use it inside J2EE containers (see [FAQ](https://logging.apache.org/log4j/1.2/faq.html#a3.6)).
193
194### Logback Example
195
196Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!*
197
198It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
199By default, only messages with ERROR level or higher are logged.
200
201It also turns on slow query tracing as described above.
202
203```xml
204<?xml version="1.0" encoding="UTF-8"?>
205<configuration>
206
207 <!-- log INFO or higher messages to the console -->
208 <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
209 <encoder>
210 <pattern>%-5p %msg%n</pattern>
211 </encoder>
212 </appender>
213
214 <!-- log everything to a rolling file -->
215 <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
216 <file>driver.log</file>
217 <encoder>
218 <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern>
219 </encoder>
220 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
221 <!-- daily rollover -->
222 <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern>
223 <!-- keep 30 days' worth of history -->
224 <maxHistory>30</maxHistory>
225 </rollingPolicy>
226 </appender>
227
228 <!-- use AsyncAppender for lower latencies -->
229 <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
230 <appender-ref ref="console" />
231 <appender-ref ref="file" />
232 </appender>
233
234 <!--
235 Turn on slow query logging by setting this logger to DEBUG;
236 set level to TRACE to also log query parameters
237 -->
238 <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" />
239
240 <root level="ERROR">
241 <appender-ref ref="async" />
242 </root>
243
244</configuration>
245```
246
247### Log4J Example
248
249Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!*
250
251It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
252By default, only messages with ERROR level or higher are logged.
253
254It also turns on slow query tracing as described above.
255
256```xml
257<log4j:configuration>
258
259 <!-- log INFO or higher messages to the console -->
260 <appender name="console" class="org.apache.log4j.ConsoleAppender">
261 <param name="threshold" value="INFO"/>
262 <layout class="org.apache.log4j.PatternLayout">
263 <param name="ConversionPattern" value="%-5p %m%n"/>
264 </layout>
265 </appender>
266
267 <!-- log everything to a rolling file -->
268 <appender name="file" class="org.apache.log4j.RollingFileAppender">
269 <param name="file" value="driver.log"/>
270 <param name="append" value="false"/>
271 <param name="maxFileSize" value="1GB"/>
272 <param name="maxBackupIndex" value="10"/>
273 <layout class="org.apache.log4j.PatternLayout">
274 <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/>
275 </layout>
276 </appender>
277
278 <!-- use AsyncAppender for lower latencies -->
279 <appender name="async" class="org.apache.log4j.AsyncAppender">
280 <param name="BufferSize" value="500"/>
281 <appender-ref ref="file"/>
282 <appender-ref ref="console"/>
283 </appender>
284
285 <!--
286 Turn on slow query logging by setting this logger to DEBUG;
287 set level to TRACE to also log query parameters
288 -->
289 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
290 <level value="DEBUG"/>
291 </logger>
292
293 <root>
294 <priority value="ERROR"/>
295 <appender-ref ref="async"/>
296 </root>
297
298</log4j:configuration>
299```
300
301[query_logger]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryLogger.html