How to use Twitter as an error log

by Richard Bradshaw

Sure this has been done before, but I had a brainwave today – why not use Twitter as an error log for web apps?

I already have error handling on my functions, so surely this shouldn’t be a difficult addition… turns out it’s not.

First, you’ll need a twitter account. I’d recommend setting one up, then protecting the updates. Keep the username and password, you’ll need them in a minute. I’d then follow the new account you set up, as well as anyone else on your team.

Then, define a function as follows in PHP, preferably in a global include or some such thing.

function tweet_error ($error, $description) {
	$username = 'yourusername';
	$password = 'yourpassword';
	$status = "#$error - $description";
 
	$update_url = 'http://www.twitter.com/statuses/update.xml'; // http://identi.ca/api/statuses/update.xml will use identi.ca instead.
 
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, "$update_url");
	curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_POST, 1);
	curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status");
	curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
 
	$result = curl_exec($curl);
	$resultArray = curl_getinfo($curl);
 
	curl_close($curl);
 
	return ($resultArray['http_code'] == 200);
}

My function here takes two parameters, the error code as well as a description. You could generalise this and rejig it a bit, as well as perhaps changing the $status variable to look different.

For instance,

$status = "d username #$error - $description";

or

$status = "@username #$error - $description";

to send it to you. You could even define different usernames for different types of errors, if you are in a team.

In your code, then call it like this:

tweet_error ("404", $_SERVER[SCRIPT_URL]);

to log a 404, as well as the page it came from, or:

tweet_error ("DB-Connect", "Failed");

In your database connection script, or even:

tweet_error ("Possible spam", "From user XXXX");

in your comment/email form handling.

Hope this comes in useful!

Random Posts