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
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") @Validated public class ProductSearchController {
Validating query params in a Spring controller
validation
pagination
rest-api
Intermediate
8 steps
java
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = PasswordsMatchValidator.class) public @interface PasswordsMatch {
Custom cross-field validation in Spring
bean-validation
custom-constraints
cross-field-validation
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
Intermediate
9 steps
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
java
@Component public class HeaderMergeFilter { private static final String PER_REQUEST_HEADERS = HeaderMergeFilter.class.getName() + ".headers";
Merging default and per-request headers in Spring
webclient
filters
http-headers
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.