Knowledge Base
MilesWeb / Web Hosting FAQ

Steps to Enable PHP Error Logging & Automation

Approx. read time : 10 min

If you are a good developer, you might be always having a keen attention on the potential errors while developing a web application. You might be setting up workflows in a way to help you log errors properly. With PHP, you get some of the most robust method to manage the PHP error logs which can be logged manually and then automated. You will also find some third party tools that are developed by the open source community for handling the PHP error logging process.

What you should think upon is that when the errors should be logged and how that should be done? While working in the dev mode, you can log PHP errors as per your preference. You can create a PHP error log file or save them as notifications on different channels. You can always log errors conveniently as per your requirements.

Steps to Automate PHP Error Logging

  • Getting Started with PHP Error Logging
  • Enabling Error Logging in php.ini
  • Copying PHP Error Logs to File
  • Error logging in PHP Frameworks
  • Error Logging In Laravel
  • Automating PHP Error Logging Process
  • Bottom Line
  • For now, when you are working in a production mode, you should create a smooth workflow to log errors in the backend, so that the users don’t face any glitch during runtime execution.

    In this article, you will get some handy PHP error logging tips which can be helpful for potential developers.

    Getting Started with PHP Error Logging

    PHP is the most popular and widely used programming language for developing web applications. As per the builtwith insights, today almost 37,805,937 websites use PHP as their backend language, which makes it around 75% of all the websites in the world. These stats clearly display that PHP still has a highest market share in the programming world.

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

    Let’s imagine that you are connecting MySQL database with PHP and if it fails to connect with it, you can log errors in PHP as below:

    <?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");
    }
    ?>

    Enabling Error Logging in php.ini

    In order to log errors in PHP, open the php.ini file and uncomment/add the below 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

    For enabling the 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 should enable only one statement to parse the log errors in php.ini file:

    display_errors = on.

    With this 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);

    Copying PHP Error Logs to File

    The above mentioned practices work well when you work in the dev environment. But, while taking your website live and starting your work in the production mode, it is essential to hide the errors from on screen display and log them within a backend file. These can be saved 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 have a tendency 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 as below:

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

    In case you are using cPanel, the master log file, the thing you’re looking for is stored (by default) at:

    /usr/local/apache/logs/error_log

    If everything fails, you can check the PHP error logs location with the below code:

    <?php phpinfo(); ?>

    Error Logging in PHP Frameworks

    The above steps are for core PHP development. PHP has several 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 comprise of: Laravel, CodeIgniter and Symfony.

    Error Logging In Laravel

    After setting up a new Laravel project, error logging and exception handling come pre-configured in it. Laravel has a separate class App\Exceptions\Handler that handles all these issues. For logging Laravel errors, it uses the Monolog library that supports array of log handlers. Several of these handlers are configured by Laravel for you, letting you to choose between a single PHP error log file, rotating log files and writing error information to the system log.

    You can configure the PHP debug option in config/app.php file to log the errors on the display of user. This option’s value can be set in .env file under property APP_DEBUG which is an environment variable, thus setting up in app.php file. When the development is done locally, the value can be set to true, and after migrating to production, it should be set as false. Otherwise, the security concern always remains there, as it shows error on browser screen.

    Being the developer, you can save Laravel log information on a single file, daily file, syslog and the errorlog. For configuring these options for Laravel error logging, open app.php file and edit the log option. For example, if you want to setup daily logging for errors, follow the below code:

    'log' => 'daily'

    Monolog is enable to log errors with different security warnings. It adds all the errors in storage by default, but you can identify them as error, alert, emergency, critical and warning. For this, add ‘log_level’ property in options as below:

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

    You will get the log file in storage/logs. Log facades can also be used to log errors.

    <?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 comprises of a default logger that can be injected into controller showing different warning levels. Log entries are written in the var/log/dev.log file by default when you’re in the dev environment. Logs are written in the var/log/prod.log in the production environment.

     

    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',
       ]);
       // ...
    }

    Symfony being the parent framework for Laravel, the warning levels of the framework will be the same.

    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

    Monolog is used by Symfony for error logging and Symfony pre-configures some basic handlers in the default monolog.yaml. Check the below example that 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

    The complete work of error logging can be done manually, but while working in multiple teams and larger projects, you must setup an automated workflow which can log errors in third party services like Slack, Sentry, Blackfire etc.

    With these tools you can get a better understanding of errors and their solutions. It is possible to setup Slack channels to send quick notifications to the teams about any runtime incidents.

    Suppose that you have already setup Slack channel and webhooks as below:

    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

    In the above example, you will also find the emojis setup? This indicates the ways you can send Slack notifications to any particular channel as per your needs.

    Bottom Line

    This article demonstrates the ways to log errors in PHP by configuring the php.ini file. Since error handling is one of the critical tasks of website developers, and knowing the right way to log errors, in both modes– dev and production – is a serious job for them. This article displays an easy process for enabling and automating PHP error logging, without disturbing the dev.

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

Pallavi is a Digital Marketing Executive at MilesWeb and has an experience of over 4 years in content development. She is interested in writing engaging content on business, technology, web hosting and other topics related to information technology.

Trusted By Thousands of Clients & Big Businesses

We highly appreciate the kind and stellar feedback we receive from our customers. Delivering the best is our goal! MilesWeb is rated Excellent out of 5 based on reviews. Read more reviews.

Excellent
Based on reviews
2 hours ago
Perfect and Valuable Server + ...
I am using MilesWeb Servers, The main thing which I getting are continuous support over everything w...
Gunjan Makwana
4 hours ago
Milesweb is superb Hosting pro...
Milesweb is superb Hosting provider ever, their Support team is amazing!!!...
Abhishek Singh
15 hours ago
Great support in great timing...
We need urgent assistance on changes in a primary domain on our client's Cpanel accounts and reached...
Riyaju Deen
21 hours ago
Best Website Hosting platform ...
I was new on MilesWeb. And needed help on multiple areas from setting up to getting started with cre...
Harshada
1 days ago
Very quick and helpful assista...
Very quick and helpful assistance. Support person listened properly and provided a nice solution....
Narendra
1 days ago
the team is very supportive th...
the team is very supportive though at times effort needs to be made to make understand the problem s...
Suree Sharma
1 days ago
I am using miles web for 3plus...
I am using miles web for 3plus years, very quick and perfect support by the team, they helped me man...
Sri Raghav
2 days ago
The service is good...
The service is good. They are answering with patience and doing the needful as soon as possible....
MR
2 days ago
Perfect and Valuable Server + ...
I am using MilesWeb Servers, The main thing which I getting are continuous support over everything w...
Gunjan Makwana
3 days ago
Very quick and helpful assista...
Very quick and helpful assistance. Support person listened properly and provided a nice solution....
Narendra
4 days ago
positively helped me with find...
positively helped me with finding insecure content on my website causing SSL to not work properly on...
Thaviraj Junglee
4 days ago
Exceptional support, Truly Pra...
I had opted for the basic wordpress hosting plan as I intended to experiment with various plug-ins. ...
Aseem Chandna