Arrow

Logging actions to a file in WordPress

First published on September 12, 2010

If you’re writing a WordPress plugin, you might want to log certain actions, whether that’s an editing audit log, a specific visitor action, or really anything related to your site. One convenient, accessible, and useful option is to log such activities to a file.

There are several things to consider when logging information to a file, including date-stamping, basic formatting, and maximum log file sizes combined with automatic file rotation (when the log file reaches a certain file size, it is renamed to something like logfile.txt.1 and a new logfile.txt is started). This makes the log activities traceable, easy to read, and manageable on the server.

eZ Publish, an open source, enterprise-grade content management framework, has a general purpose eZLog class that already handles file logging. I’ve very slightly modified it for use within WordPress. Here is an example plugin that logs password change requests (normally sent as e-mails to the site administrator) to a file: peters_file_logs.txt

You can easily re-purpose the eZLog class for your own needs. Its write method simply takes the message to be logged, the log file name, and the path to the log file:

$message = 'Logging this';
$logger = new eZLog();
$logFile = 'wp-logs.txt';
$logPath = WP_CONTENT_DIR;
$logger->write( $message, $logFile, $logPath );

The code above would produce something like the following on a new line in wp-content/wp-logs.txt each time it is run:

[ Aug 21 2010 12:21:07 ] Logging this

You can of course customize the messages logged to add relevant information such as who performed the action, on what page, and so on. You can also customize the maximum number of rotated log files to keep and the maximum size of a log file.

Arrow

One Response to “Logging actions to a file in WordPress”


  1. Ozh says:

    Suggestion for improvement: support arrays and objects so you can $logger->write( $array )

    Also, instead of fopen you can simply use error_log( $message, 3, $file )

    Reply from Peter: Thanks for the tips. However, aren’t you susceptible to general PHP logging being turned off if you use error_log?

Speak your mind

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word