Log files in PHP

From the vast arsenal of tools and trick a PHP developer has access to, application logs might be the most underestimated and unserutilized of all. Despite the fact that they offer plenty of actionable information, it is often the last place a developer would check when trying to resolve a problem.

The truth is, log files are the resedue of your application processes and should be the first place to check when problems come. In practice the time spent debugging is significatly reduced when using php log files, in comparison to when not.

Ofcourse, log files contain information not only about problems, but also about the application processes in general. It CAN be a source of valuable information, and answer the questions about your product – What browsers are common amongst your users? How long a it takes for PHP script to finish? What pages are mostly visited in my application? And many more.

In PHP, log message destionation is mostly controlled with configuration entries (from php.ini file). Here’s the list of relevan config keys

  1. log_errors – controls if the log file is written
  2. error_log – a full path to a log file, where to write the messages
  3. display_errors – controls if the messages (writtent to log file) should be printed out to user
  4. error_reporting – controls which error level should be written to log files / printed to user

These configuration can be adapted to the environment of your application. If you are currently writing and testing code in PHP, then it’s very helpful to display debug / error messages right away. When the application is deployed and running in production, it would be wise to hide errors from the customer, but, nonetheless, write them down into a log file. This log file can later be used to find out what happened and why.

You can set the configurations in the beginning of your script, so that you always have control over what’s happening with our logs.

Development configurations example – log everything into a local file, also display every message the system generates, capture messages from every everity.

ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/dev.log');
ini_set('display_errors', 1);

Another configurations example, more appropriate for production. Log everything except notices, do not show any errors.

ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/prod.log');
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_NOTICE);

This approach makes for a good starting point with log files, but I personally prefer using log files not only for debug / problem solving, but for development overall.

The best way to view debug information is listening for the log file when doing development. Apart from IDE and Browser opened, I always have a terminal running with the following command, which outputs last information from the log file

tail -f ./dev.log

Happy logging!