Elffuss BraidHub

kikocis/java-driver public

3.1.x · 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* `com.datastax.driver.core.Message`
111 * TRACE
112 * Custom payloads
113
114### Logging query latencies
115
116The `QueryLogger` provides clients with the ability to log queries
117executed by the driver, and especially, it allows client to track slow
118queries, i.e. queries that take longer to complete than a configured
119threshold in milliseconds.
120
121To turn on this feature, you first need to instantiate and register a `QueryLogger` instance:
122
123```java
124Cluster cluster = ...
125QueryLogger queryLogger = QueryLogger.builder()
126 .withConstantThreshold(...)
127 .withMaxQueryStringLength(...)
128.build();
129cluster.register(queryLogger);
130```
131
132Note that `QueryLogger` instances are thread-safe and can be shared cluster-wide.
133Besides, you can adjust several parameters such as the maximum query string length to be printed,
134the maximum number of parameters to print, etc. Refer to the
135`QueryLogger` [API docs][query_logger] for more information.
136
137Secondly, you need to adjust your logging framework to accept log messages from the `QueryLogger`. The `QueryLogger`
138uses 3 different loggers:
139
140* `com.datastax.driver.core.QueryLogger.NORMAL` : Used to log normal queries, i.e., queries that completed successfully within a configurable threshold in milliseconds.
141* `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.
142* `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.
143
144You need to set the above loggers to DEBUG level to turn them on. E.g. to track queries
145that take more than 300 ms to complete, configure your `QueryLogger` with that threshold (see above),
146then set the `com.datastax.driver.core.QueryLogger.SLOW` logger to DEBUG, e.g. with Log4J:
147
148```xml
149 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
150 <level value="DEBUG"/>
151 </logger>
152```
153
154The `QueryLogger` would then print messages such as this for every slow query:
155
156```
157DEBUG [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=?;
158```
159
160As 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
161to TRACE instead, e.g. with Log4J:
162
163```xml
164 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
165 <level value="TRACE"/>
166 </logger>
167```
168
169The `QueryLogger` would then print messages such as this for every slow query:
170
171```
172TRACE [cluster1] [/127.0.0.1:9042] Query too slow, took 329 ms: SELECT * FROM users WHERE user_id=? [user_id=42];
173```
174
175Be careful when logging large query strings (specially batches) and/or queries with considerable amounts of parameters.
176See the `QueryLogger` [API docs][query_logger] for examples of how to truncate the printed message when necessary.
177
178#### Constant vs Dynamic thresholds
179
180Currently the `QueryLogger` can be configured to track slow queries using either
181a constant threshold in milliseconds (which is the default behavior), or
182a dynamic threshold based on per-host latency percentiles, as computed by `PerHostPercentileTracker`.
183
184**Dynamic thresholds are still a beta feature: they haven't been extensively
185tested yet, and the API is still subject to change.**
186
187Refer to the `QueryLogger` [API docs][query_logger] for an example of usage.
188
189### Performance Tips
190
191* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html)
192and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders
193that can significantly boost latencies when writing log messages.
194* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration
195without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html);
196Log4J 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)).
197
198### Logback Example
199
200Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!*
201
202It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
203By default, only messages with ERROR level or higher are logged.
204
205It also turns on slow query tracing as described above.
206
207```xml
208<?xml version="1.0" encoding="UTF-8"?>
209<configuration>
210
211 <!-- log INFO or higher messages to the console -->
212 <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
213 <encoder>
214 <pattern>%-5p %msg%n</pattern>
215 </encoder>
216 </appender>
217
218 <!-- log everything to a rolling file -->
219 <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
220 <file>driver.log</file>
221 <encoder>
222 <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern>
223 </encoder>
224 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
225 <!-- daily rollover -->
226 <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern>
227 <!-- keep 30 days' worth of history -->
228 <maxHistory>30</maxHistory>
229 </rollingPolicy>
230 </appender>
231
232 <!-- use AsyncAppender for lower latencies -->
233 <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
234 <appender-ref ref="console" />
235 <appender-ref ref="file" />
236 </appender>
237
238 <!--
239 Turn on slow query logging by setting this logger to DEBUG;
240 set level to TRACE to also log query parameters
241 -->
242 <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" />
243
244 <root level="ERROR">
245 <appender-ref ref="async" />
246 </root>
247
248</configuration>
249```
250
251### Log4J Example
252
253Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!*
254
255It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
256By default, only messages with ERROR level or higher are logged.
257
258It also turns on slow query tracing as described above.
259
260```xml
261<log4j:configuration>
262
263 <!-- log INFO or higher messages to the console -->
264 <appender name="console" class="org.apache.log4j.ConsoleAppender">
265 <param name="threshold" value="INFO"/>
266 <layout class="org.apache.log4j.PatternLayout">
267 <param name="ConversionPattern" value="%-5p %m%n"/>
268 </layout>
269 </appender>
270
271 <!-- log everything to a rolling file -->
272 <appender name="file" class="org.apache.log4j.RollingFileAppender">
273 <param name="file" value="driver.log"/>
274 <param name="append" value="false"/>
275 <param name="maxFileSize" value="1GB"/>
276 <param name="maxBackupIndex" value="10"/>
277 <layout class="org.apache.log4j.PatternLayout">
278 <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/>
279 </layout>
280 </appender>
281
282 <!-- use AsyncAppender for lower latencies -->
283 <appender name="async" class="org.apache.log4j.AsyncAppender">
284 <param name="BufferSize" value="500"/>
285 <appender-ref ref="file"/>
286 <appender-ref ref="console"/>
287 </appender>
288
289 <!--
290 Turn on slow query logging by setting this logger to DEBUG;
291 set level to TRACE to also log query parameters
292 -->
293 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
294 <level value="DEBUG"/>
295 </logger>
296
297 <root>
298 <priority value="ERROR"/>
299 <appender-ref ref="async"/>
300 </root>
301
302</log4j:configuration>
303```
304
305[query_logger]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryLogger.html