Wordpress - How do I log plugin (cron) actions?
Use a logging function like this, so that it writes your log out to debug.log by configuring your wp-config.php with the following which I found here:
/**
* This will log all errors notices and warnings to a file called debug.log in
* wp-content (if Apache does not have write permission, you may need to create
* the file first and set the appropriate permissions (i.e. use 666) )
*/
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors',0);
This should work for debugging/development purposes at least (I'm not sure how great it would be for production logging, but it works for development.)
Use a file to write the events to. There are several drawbacks here;
- Filesystem permissions. When you deploy your app, you will have to take care to remember to give the webserver permission to write to the file. And to be extra sure, you'd have to write code which checks whether you can write to the file and issue a warning when you can't. This adds complexity and is likely a cause for deployment issues.
- Accidental deletion. You could accidentally delete the custom logfile and loose your records. This might be inconvenient.
- Custom logformat. You'd have to come up with a custom (machine readable?) text format to write the events to your file. When you have to change the log format, there's no convenient way to migrate old records. When you want to do some kind of analysis on the logs, you'd have to parse the records. This leads to more code and more complexity. Complexity is bad.
Use a database table. Create your own database table and log the events there. None of the drawbacks listed above apply. It doesn't add a lot of complexity. Automate the creation and deletion of the table using a plugin hook and you have a reasonably reliable log system I think.
Send an e-mail. Depending on the relevance of the logs, you could always opt for this method. I figure you'd probably want to send an e-mail in case of a failure anyway.
Use the OS logger. When you use the syslog function in PHP, you can write events to the system logger (syslog on Unix, Event Log on Windows NT). Configuring a user defined syslog complicates deployment.
Finally; you should consider if you want to log the normal case and exceptions, or only exceptions. Jeff Atwood did a good writeup about this.
Hope this helps!
I agree, putting this data in wp_posts
could potentially make the table grow quickly to an unmanageable size. It's fine to create a table. I would go the extra mile and give someone a way to cleanup the log table in the event they stop using their plugin.
I'm not afraid of plugins that create tables, but maybe that's because I've seen WordPress databases with 8,000,000 wp_term_relationships
records and 300,000 posts and I know how unpleasant that experience can be.
dbDelta()
and register_activation_hook()
will be your friends, here. See Creating Tables with Plugins.