WP-Mix

A fresh mix of code snippets and tutorials

Add Custom Info to PHP System Log

Here is a quick function for adding custom information to the system log via PHP.

Hook the following function into any PHP script and you’re good to go:

function custom_log($prepend = '', $message) {
	openlog($prepend, LOG_NDELAY|LOG_PID, LOG_AUTH);
	syslog(LOG_INFO, $message);
	closelog();
	// die(); // optional
}

This is a bare-bones logging function that does the following:

  1. Opens a connection to the system logger
  2. Writes a message to the system log file
  3. Closes the connection
  4. Dies (optional, uncomment to enable)

The function accepts two variables:

  • $prepend – string that prepended to each message
  • $message – string containing the message

Let’s look at an example.

Example

Let’s say that we want to add a custom log message that records the visitor’s IP address as some point in the PHP script. After including the complete custom_log() elsewhere in the script, call it like so:

$prepend = 'Custom';
$message = 'Current IP Address: '. $_SERVER['REMOTE_ADDR'];
custom_log($prepend, $message)

With this in place, the IP address will be recorded in the system log.

There are a million ways to use this simple function. I use it when troubleshooting stuff, it helps to have key info all in one place while investigating issues, etc.

References

Learn more about the PHP functions used in the custom_log() function:

★ Pro Tip:

USP Pro