WordPress Custom Logs

Written by
Published
Updated
Typical Read
1 minutes

WordPress has logging functionality built-in & easy to add to, but what if you want to create your own WordPress custom log file for a plugin or theme?

Tracking down issues, or storing non-sensitive information is a cinch with WordPress custom logs. Easily add debugging statements to help zero-in on bugs or log useful information using the fopen and fwrite functions.

tl;dr

/**
 * Write an entry to a log file in the uploads directory.
 * 
 * @since x.x.x
 * 
 * @param mixed $entry String or array of the information to write to the log.
 * @param string $file Optional. The file basename for the .log file.
 * @param string $mode Optional. The type of write. See 'mode' at https://www.php.net/manual/en/function.fopen.php.
 * @return boolean|int Number of bytes written to the lof file, false otherwise.
 */
if ( ! function_exists( 'plugin_log' ) ) {
  function plugin_log( $entry, $mode = 'a', $file = 'plugin' ) { 
    // Get WordPress uploads directory.
    $upload_dir = wp_upload_dir();
    $upload_dir = $upload_dir['basedir'];

    // If the entry is array, json_encode.
    if ( is_array( $entry ) ) { 
      $entry = json_encode( $entry ); 
    } 

    // Write the log file.
    $file  = $upload_dir . '/' . $file . '.log';
    $file  = fopen( $file, $mode );
    $bytes = fwrite( $file, current_time( 'mysql' ) . "::" . $entry . "\n" ); 
    fclose( $file ); 

    return $bytes;
  }
}

Usage

// Append an entry to the uploads/plugin.log file.
plugin_log( 'Something happened.' );

// Append an array entry to the uploads/plugin.log file.
plugin_log( ['new_user' => 'benmarshall' ] );

// Write an entry to the uploads/plugin.log file, deleting the existing entries.
plugin_log( 'Awesome sauce.', 'w' );

// Append an entry to a different log file in the uploads directory.
plugin_log( 'Simple stuff.', 'a', 'simple-stuff' );

IMPORTANT: Never store personally identifiable information or sensitive data in log files. These are typically publicly accessible for anyone to read.

Customize the function as needed, but keep in mind that some hosts such as Pantheon don’t allow (at least easily) you to write files outside the uploads directory.

Join the conversation.

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

All comments posted on 'WordPress Custom Logs' are held for moderation and only published when on topic and not rude. Get a gold star if you actually read & follow these rules.

You may write comments in Markdown. This is the best way to post any code, inline like `<div>this</div>` or multiline blocks within triple backtick fences (```) with double new lines before and after.

Want to tell me something privately, like pointing out a typo or stuff like that? Contact Me.