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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A proxy DataSource lets you observe every query without touching application or ORM code.
- 2Building the real Hikari pool from DataSourceProperties keeps Spring Boot's normal configuration intact underneath the wrapper.
- 3An execution listener can compare elapsed time against a threshold to surface only the queries worth investigating.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/wrapping-a-spring-datasource-for-query-tracing-explained-java-27c2/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.