Save WordPress debug log by date

It’s not recommended to keep debugging enabled on a production site. But sometimes you may need to in order to gain the data you need.

The danger is that error logging writes to a text file, and the larger that file becomes, the more it degrades your system performance. If you ignore it completely, it can crash your site.

This article outlines a way to automatically save the debug log by date so you can maintain smaller file size for the log, which will help avoid performance issues. This also makes it easier to find logs for specific dates, since the date is part of the file name (at least in this example).

It’s important to note that the error_log() function used to log errors is not a WordPress function. People mislabel this all the time and spend time looking for the WP function; but it’s actually a PHP function.

The primary action that WP enacts when the debug log is enabled is to write the log file to /wp-content/debug.log. Adding the following somewhere in your site (can be in your wp-config.php, in a plugin, or in your theme’s functions.php file) will set a filename for the debug.log file in the format of debug-2020-01-01.log.

ini_set( 'error_log', WP_CONTENT_DIR . '/debug-' . date('Y-m-d') . '.log' );

Note that this is not really a secure process. Your log files are still openly available if someone knows the naming convention being used. To protect your log files from prying eyes, I recommend adding a hash to the filename. This way, the file name has some randomness to it. In order to work successfully, you’ll need to store the hash for the day, so you create one hash for the day and use it for all writes to the log file.

// Get stored hashes.
$error_log_hashes = get_option( 'error_log_hashes' );
// Get today's date.
$date = date('Y-m-d');
// Check if there is a hash for today. If not, create one.
if ( isset( $error_log_hashes[ $date ] ) ) {
    $hash = $error_log_hashes[ $date ];
} else {
    // Generate a random value with NO special characters.
    $hash = wp_generate_password( 12, false, false );
    // Update the hashes so we use this on subsequent requests this day.
    $error_log_hash[ $date ] = $hash;
    update_option( 'error_log_hashes', $error_log_hashes );
}

$log_file = 'debug-' . $hash . '-' . $date . '.log';
$error_log_file = WP_CONTENT_DIR . '/debug-' . $date . '.log';

ini_set( 'error_log', $error_log_file );

Leave a comment

Your email address will not be published. Required fields are marked *