Introduction to Logging and Tracing in PHP

If you still tracing variable in php using print_r() or var_dump() then you’ll see them directly in the screen or the web page that you’re working on. This is easy to see, but also prone to problems:

  1. What if visitors see your error trace? Surely you don’t want that.
  2. What if you have a function call that relies on no string has been printed yet, e.g.: header(), ini_set(), these functions will fail and depending on your settings most likely when they fail they don’t show any sign of error.

Best way to do code tracing in PHP is to write the following code into your file – one of the early-executed file, such as config/header file, where you don’t have any output yet:

1
2
3
ini_set('log_errors','On');
ini_set('error_log', '/var/wwwtmp/php.log');
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

And at the part where you want to trace a certain variable

1
error_log(__FILE__.' ('.__LINE__.') '.__CLASS__.' :: '. __FUNCTION__ .' :: '. print_r($YOUR_VARIABLE_HERE,true));

By default apache2 and php will output their error in /var/log/apache2/error.log ,but after executing the ini_set above, the error log will be produced in /var/wwwtmp/php.log. And you need to make sure you that directory exists, if not use other directory that www-data has write access to. Why do we need to setup in a different location? Because the default file output doesn’t support showing new lines, you’ll see lot’s of \n. Thus make tracing hard to read.

This entry was posted in php, Web Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 1 = two