java 46 lines · 7 steps

Wrapping a Spring DataSource for query tracing

A Spring @Bean wraps HikariCP in a proxy that logs every query and flags slow ones with their parameters.

Explained by highlit
1@Configuration
2public class DataSourceLoggingConfig {
3 
4 @Bean
5 public DataSource dataSource(DataSourceProperties properties) {
6 HikariDataSource target = properties.initializeDataSourceBuilder()
7 .type(HikariDataSource.class)
8 .build();
9 
10 return ProxyDataSourceBuilder.create(target)
11 .name("traced-ds")
12 .listener(new SlowQueryListener(Duration.ofMillis(500)))
13 .logQueryBySlf4j(SLF4JLogLevel.DEBUG, "sql.query")
14 .multiline()
15 .build();
16 }
17 
18 static class SlowQueryListener implements QueryExecutionListener {
19 
20 private static final Logger log = LoggerFactory.getLogger("sql.slow");
21 private final long thresholdNanos;
22 
23 SlowQueryListener(Duration threshold) {
24 this.thresholdNanos = threshold.toNanos();
25 }
26 
27 @Override
28 public void beforeQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
29 }
30 
31 @Override
32 public void afterQuery(ExecutionInfo execInfo, List<QueryInfo> queryInfoList) {
33 if (execInfo.getElapsedTime() * 1_000_000L < thresholdNanos) {
34 return;
35 }
36 for (QueryInfo query : queryInfoList) {
37 String params = query.getParametersList().stream()
38 .flatMap(List::stream)
39 .map(p -> p.getArgs()[0] + "=" + p.getArgs()[1])
40 .collect(Collectors.joining(", "));
41 log.warn("Slow query {}ms: {} [{}]",
42 execInfo.getElapsedTime(), query.getQuery(), params);
43 }
44 }
45 }
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A proxy DataSource lets you observe every query without touching application or ORM code.
  2. 2Building the real Hikari pool from DataSourceProperties keeps Spring Boot's normal configuration intact underneath the wrapper.
  3. 3An execution listener can compare elapsed time against a threshold to surface only the queries worth investigating.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Wrapping a Spring DataSource for query tracing — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code