REST API & Developer PHP Advanced

Log Slow Database Queries

Write any database query that takes longer than 50 ms to the PHP error log, with the function that ran it.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 23 lines
add_action( 'shutdown', function (): void {
	global $wpdb;

	if ( ! defined( 'SAVEQUERIES' ) || ! SAVEQUERIES || empty( $wpdb->queries ) ) {
		return;
	}

	$threshold = 0.05; // Seconds.
	$url       = esc_url_raw( $_SERVER['REQUEST_URI'] ?? '' );

	foreach ( $wpdb->queries as $query ) {
		[ $sql, $time, $caller ] = $query;
		if ( $time >= $threshold ) {
			error_log( sprintf(
				'[slow query] %.3fs %s | %s | %s',
				$time,
				$url,
				$caller,
				preg_replace( '/\s+/', ' ', substr( $sql, 0, 500 ) )
			) );
		}
	}
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

A slow page is often caused by one or two slow database queries, usually from a plugin. This snippet records them so you can find out which code is responsible.

How it works

When SAVEQUERIES is on, WordPress records every query with its run time and the chain of functions that called it. At the end of the request, on shutdown, the snippet goes through that list and writes anything over the threshold to the error log.

The log line includes the time, the page URL, the caller and the start of the SQL.

Things to watch

  • Add define( 'SAVEQUERIES', true ); to wp-config.php to turn it on, and remove it when you’re done. Saving every query uses extra memory on every request.
  • Use it on staging, or on production for a short time only.
  • Query Monitor shows the same information in a panel if you’d rather not read logs.

How to test it

Turn on SAVEQUERIES, set the threshold to 0 and load a page. Your error log should list its queries. Then set it back to 0.05.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only