Elffuss BraidHub

kikocis/java-driver public

6cbc334fa86f · 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 per-host latency percentiles, as computed by `PerHostPercentileTracker`.
180
181**Dynamic thresholds are still a beta feature as of version 2.1.6: they
182haven't been extensively tested yet, and the API is still subject to
183change.**
184
185Refer to the `QueryLogger` [API docs][query_logger] for an example of usage.
186
187### Performance Tips
188
189* Use asynchronous appenders; both [Log4J](http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/AsyncAppender.html)
190and [Logback](http://logback.qos.ch/manual/appenders.html#AsyncAppender) provide asynchronous appenders
191that can significantly boost latencies when writing log messages.
192* While the driver does not provide such capability, it is possible for client applications to hot-reload the log configuration
193without stopping the application. This usually involves JMX and is available for [Logback](http://logback.qos.ch/manual/jmxConfig.html);
194Log4J 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)).
195
196### Logback Example
197
198Here is a typical example configuration for Logback. *Please adapt it to your specific needs before using it!*
199
200It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
201By default, only messages with ERROR level or higher are logged.
202
203It also turns on slow query tracing as described above.
204
205```xml
206<?xml version="1.0" encoding="UTF-8"?>
207<configuration>
208
209 <!-- log INFO or higher messages to the console -->
210 <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
211 <encoder>
212 <pattern>%-5p %msg%n</pattern>
213 </encoder>
214 </appender>
215
216 <!-- log everything to a rolling file -->
217 <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
218 <file>driver.log</file>
219 <encoder>
220 <pattern>%-5p [%d{ISO8601}] [%t] %F:%L - %msg%n</pattern>
221 </encoder>
222 <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
223 <!-- daily rollover -->
224 <fileNamePattern>driver.%d{yyyy-MM-dd}.log</fileNamePattern>
225 <!-- keep 30 days' worth of history -->
226 <maxHistory>30</maxHistory>
227 </rollingPolicy>
228 </appender>
229
230 <!-- use AsyncAppender for lower latencies -->
231 <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
232 <appender-ref ref="console" />
233 <appender-ref ref="file" />
234 </appender>
235
236 <!--
237 Turn on slow query logging by setting this logger to DEBUG;
238 set level to TRACE to also log query parameters
239 -->
240 <logger name="com.datastax.driver.core.QueryLogger.SLOW" level="DEBUG" />
241
242 <root level="ERROR">
243 <appender-ref ref="async" />
244 </root>
245
246</configuration>
247```
248
249### Log4J Example
250
251Here is a typical example configuration for Log4J. *Please adapt it to your specific needs before using it!*
252
253It logs messages to the console with levels equal to or higher than INFO, and logs all messages to a rolling file.
254By default, only messages with ERROR level or higher are logged.
255
256It also turns on slow query tracing as described above.
257
258```xml
259<log4j:configuration>
260
261 <!-- log INFO or higher messages to the console -->
262 <appender name="console" class="org.apache.log4j.ConsoleAppender">
263 <param name="threshold" value="INFO"/>
264 <layout class="org.apache.log4j.PatternLayout">
265 <param name="ConversionPattern" value="%-5p %m%n"/>
266 </layout>
267 </appender>
268
269 <!-- log everything to a rolling file -->
270 <appender name="file" class="org.apache.log4j.RollingFileAppender">
271 <param name="file" value="driver.log"/>
272 <param name="append" value="false"/>
273 <param name="maxFileSize" value="1GB"/>
274 <param name="maxBackupIndex" value="10"/>
275 <layout class="org.apache.log4j.PatternLayout">
276 <param name="ConversionPattern" value="%-5p [%d{ISO8601}] [%t] %F:%L - %m%n"/>
277 </layout>
278 </appender>
279
280 <!-- use AsyncAppender for lower latencies -->
281 <appender name="async" class="org.apache.log4j.AsyncAppender">
282 <param name="BufferSize" value="500"/>
283 <appender-ref ref="file"/>
284 <appender-ref ref="console"/>
285 </appender>
286
287 <!--
288 Turn on slow query logging by setting this logger to DEBUG;
289 set level to TRACE to also log query parameters
290 -->
291 <logger name="com.datastax.driver.core.QueryLogger.SLOW">
292 <level value="DEBUG"/>
293 </logger>
294
295 <root>
296 <priority value="ERROR"/>
297 <appender-ref ref="async"/>
298 </root>
299
300</log4j:configuration>
301```
302
303[query_logger]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryLogger.html