How can we log the Hikari Pool Stats in Java or Spring Boot

Spring Boot
Put below in your application.yaml or application.properties

logging.level.com.zaxxer=TRACE

If using any logger file (log4j2.xml) then add below in your xml file:

   <Logger name="com.zaxxer" additivity="false" level="trace">
            <AppenderRef ref="hikariLog"/>
            <!-- <AppenderRef ref="console"/> -->
        </Logger>

Core Java
Get the HikariDataSource object and pass in below method:

    private void logHikariStats(HikariDataSource ds) {
        HikariPoolMXBean poolMXBean = ds.getHikariPoolMXBean();
        int activeConnections = poolMXBean.getActiveConnections();
        int idleConnections = poolMXBean.getIdleConnections();
        int totalConnections = poolMXBean.getTotalConnections();
        int threadsAwaitingConnection = poolMXBean.getThreadsAwaitingConnection();
        String stats = "Total[" + totalConnections + "],Active[" + activeConnections + "],Idle[" + idleConnections + "],Waiting[" + threadsAwaitingConnection + "]";
        System.out.println("=== Hikari Stats=== " + stats);
    }
3 Likes