A fresh mix of code snippets and tutorials

PHP Error Log Tricks

Super useful trick for customizing error logs when working with PHP.

PHP makes it very easy to log your own custom entries at any point in your script. Here are some examples to illustrate how it’s done.

General example

In general, the code to use looks like this:

error_log('my_function(): did something');

Here we write our custom message to the default system error log. Can use anywhere, in any script, to log whatever is required.

More specific example

In this example, we specify a custom message when no database connection is available:

if (!db_connection) {
	error_log('Database not available.', 0);

Here the second parameter 0 specifies that the error message should be written to the default system error log.

Send log entry via email

Next is an example where we send an email when some function returns false:

if (!some_function) {
	error_log('Sup dude! Some function returned false..', 1, 'email@example.com');

The second parameter here is set as 1, which tells the script to send the message to the specified email address (in the third parameter).

Write log entry to custom location

Lastly, here is an example that shows how to write the error to a custom log file:

error_log('Whoa!!! Better tell the custom error log about this..', 3, '/var/tmp/custom-errors.log');

Here the second parameter is 3, which instructs the function to write to the specified location (i.e., our custom log). Much more is possible, check the reference links for more infos.


★ Pro Tip: