Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How to Enable PHP Error Logging & Automation

June 24, 2019

7 Min Read
PHP Error Logging
Reading Time: 7 minutes

A good developer always keeps a close eye on the potential errors while developing a web application. He always sets up those workflows that help him log errors properly. PHP offers some of the robust methods to work with PHP error logs which you can log manually and automate them. There are some third party tools as well built by the open source community to handle PHP error logging process.

The most important thing is that when you should log errors and how you should do it? When you are working in the dev mode, you can log PHP errors at your will. Either create a PHP error log file or save them as notifications on different channels, you always get the convenience to log errors as per your requirements.

Meanwhile, when you are working in a production mode, you must create a smooth workflow to enable PHP error logging, so that the users should not face any glitch during runtime execution.

In this article, I’ll mention some handy PHP error logging tips which can be helpful for budding developers.

Host Your PHP Apps With Us For 10x Faster Performance

Don’t Let Your Customers Run Away With The Downtimes. Deploy With Us Today!

Getting Started with PHP Error Logging

PHP is the most widely used programming language for developing web applications. According to the builtwith insights, today almost  37,805,937 websites are using PHP as their backend language, which makes it around 75% of all the websites in the world. These stats clearly shows that PHP still has a solid market share in the programming world.

When you start developing an application in PHP, you use few commands like print_r() ,var_dump() to debug errors and log on browser. But, that is not the safest way while working in production mode. In dev mode, you can do it, but have to disable it when initiating the migration. Hence, in dev mode, you can easily log errors in PHP with error_log() function, which sends an error message to the defined error handling routines.

Let’s suppose you are connecting MySQL database with PHP and if it fails to connect with it, you can log errors in PHP like this:

<?php

// Send error message to the server log if error connecting to the database

if (!mysqli_connect("localhost","bad_user","bad_password","my_db")) {

   error_log("Failed to connect to database!", 0);

}

// Send email to administrator if we run out of FOO

if (!($foo = allocate_new_foo())) {

   error_log("Oh no! We are out of FOOs!", 1, "admin@example.com");

}

?>

Enable Error Logging in php.ini

To log errors in PHP, open the php.ini file and uncomment/add the following lines of code.

error_reporting = E_ALL & ~E_NOTICE

error_reporting = E_ALL & ~E_NOTICE | E_STRICT

error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR

error_reporting = E_ALL & ~E_NOTICE

If you want to enable PHP error logging in individual files, add this code at the top of the PHP file.

ini_set('display_errors', 1);

ini_set('display_startup_errors', 1);

error_reporting(E_ALL);

Now, you must enable only one statement to parse the log errors in php.ini file:

display_errors = on.

Now, you can easily see logged errors in your browser. Some of the additional commands you can write for PHP error logging include:

// Turn off all error reporting

error_reporting(0);



// Report simple running errors

error_reporting(E_ERROR | E_WARNING | E_PARSE);



// Reporting E_NOTICE can be good too (to report uninitialized variables or catch variable name misspellings ...)

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);



// Report all errors except E_NOTICE

error_reporting(E_ALL & ~E_NOTICE);



// Report all PHP errors (see changelog)

error_reporting(E_ALL);



// Report all PHP errors

error_reporting(-1);



// Same as error_reporting(E_ALL);

ini_set('error_reporting', E_ALL);

Copy PHP Error Logs to File

The above defined practices work fittingly well when you are working in the dev environment. But, when you take your website live and start working in the production mode, you must hide the errors from on screen display and log them within a backend file. You can save these at a specific PHP error logs location whose URL is already described in the php.ini file.

PHP stores error logs in /var/log/apache2, if it uses an apache2 module. Shared hosts tend to store PHP error log files in your root directory /log subfolder. But…if you have access to the php.ini file you can do this by:

error_log = /var/log/php-scripts.log

If you’re using cPanel, the master log file, what you’re probably looking for is stored (by default) at:

/usr/local/apache/logs/error_log

If all else fails, you can check the PHP error logs location by using:

<?php phpinfo(); ?>

Error logging in PHP Frameworks

The above steps I’ve explained are for core PHP development. PHP has a variety of Model View Architecture (MVC) and micro-frameworks which have their own methods on top of the core functions. Some of the best PHP MVC frameworks to build advanced web applications with include: Laravel, CodeIgniter and Symfony.

Error Logging In Laravel

When you setup a new Laravel project, error logging and exception handling comes pre-configured in it. Laravel has a separate class App\Exceptions\Handler which takes care of all these issues. For logging Laravel errors, it utilizes the Monolog library which supports variety of log handlers. Laravel configures several of these handlers for you, allowing you to choose between a single PHP error log file, rotating log files and writing error information to the system log.

In config/app.php file, you can configure the PHP debug option to log the errors on the display of user. The value of this option can be set in .env file under property APP_DEBUG which is an environment variable, thus setting up in app.php file. When developing locally, the value can be set to true, and after migrating to production, it must be set to false. Otherwise, the security concern is always there as it will show error on browser screen.

You, being the developer, can save Laravel log information on a single file, daily file, syslog and the errorlog. To configure these options for Laravel error logging, you must open app.php file and edit the log option. For instance, if you want to setup daily logging for errors, you will do the following:

'log' => 'daily'

Monolog can log errors with different security warnings. By default, it adds all the errors in storage, but you can identify them as error, emergency, alert, critical and warning. To do that, add ‘log_level’ property in options like this:

'log_level' => env('APP_LOG_LEVEL', 'error'),

The log file is present in storage/logs. You can also log errors using log facades.

<?php

namespace App\Http\Controllers;

use App\User;

use Illuminate\Support\Facades\Log;

use App\Http\Controllers\Controller;



class UserController extends Controller

{

   /**

    * Show the profile for the given user.

    *

    * @param  int $id

    * @return Response

    */

   public function showProfile($id)

   {

       Log::info('Showing user profile for user: '.$id);



       return view('user.profile', ['user' => User::findOrFail($id)]);

   }

}



The logger provides eight different logging levels, including:



Log::emergency($message);

Log::alert($message);

Log::critical($message);

Log::error($message);

Log::warning($message);

Log::notice($message);

Log::info($message);

Log::debug($message);

Error Logging In Symfony

Symfony comes with a default logger which you can inject into controller showing different warning levels. By default, log entries are written in the var/log/dev.log file when you’re in the dev environment. In the production environment, logs are written in the var/log/prod.log.

use Psr\Log\LoggerInterface;



public function index(LoggerInterface $logger)

{

   $logger->info('I just got the logger');

   $logger->error('An error occurred');



   $logger->critical('I left the oven on!', [

       // include extra "context" info in your logs

       'cause' => 'in_hurry',

   ]);



   // ...

}

Since Symfony is the parent framework for Laravel, the warning levels of the framework are also the same.

Symfony also uses Monolog for error logging and pre-configures some basic handlers in the default monolog.yaml. Below is the example which uses syslogs to write logs on the file:

// config/packages/prod/monolog.php

$container->loadFromExtension('monolog', [

   'handlers' => [

       'file_log' => [

           'type' => 'stream',

           'path' => '%kernel.logs_dir%/%kernel.environment%.log',

           'level' => 'debug',

       ],

       'syslog_handler' => [

           'type' => 'syslog',

           'level' => 'error',

       ],

   ],

]);

Automating PHP Error Logging Process

You can do the whole work of error logging manually, but when you are working in multiple teams and larger projects, you must setup an automated workflow which can log errors in third party services like Sentry, Slack, Blackfire etc.

These tools can provide you a better understanding of errors and their solutions. You can also setup Slack channels to send quick notifications to the teams about any runtime incidents.

You can see this nice example in Symfony which also works in the similar fashion.

Assume you have already setup Slack channel and webhooks as:

monolog:

   handlers:

       main:

           type:  fingers_crossed

           action_level: error

           handler:  nested

       nested:

           type: stream

           path: "%kernel.logs_dir%/%kernel.environment%.log"

           level: debug

       console:

           type: console

       slack:

           type: slack

           token: xxxx-xxxxxxxxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxx

           channel: "#name-of-channel"

           bot_name: ChooseName

           icon_emoji: :ghost:

           level: critical

The emojis are also setup in the above example, have you seen that? 😀 This shows how you can send Slack notifications to any particular channel as per your needs.

How PHP Errors Are Logged on Cloudways

When you create an account on Cloudways web hosting for PHP and launch PHP server with the application, you can see the log folder at the root directory which takes care of the server logs. You can find both Apache and Nginx logs there, which help you to identify the potential error logs. Since, Cloudways does not allow users to edit php.ini file (you can ask live support agent to do that for you); but if you carefully see the PHP server settings, you can customize most of the error_reporting and logging settings in platform.

Of course, you also have access to PHP-FPM where you can add php.ini rules to log PHP errors.

Final Words

This article demonstrates in detail how to log errors in PHP by configuring the php.ini file. Because error handling is one of the core tasks of website developers, and knowing the right way to log errors – both in dev and production mode – is a serious job for them. This article presents an easy process as to how to enable and automate PHP error logging, keeping the dev work on track.

If you find this article helpful, and want to share your views about the topic, feel free to write down your suggestions in the comments section below.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at shahroze.nawaz@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!