This guide explores the basics of logging in PHP, including how to configure logging, where logs are located, and how logging can help you be more effective when troubleshooting and monitoring your PHP applications. Show
It’s always good to have a handle on the basics, so this article covers the error log built into PHP. If you’re setting up a new application or want to improve an existing one, we recommend you take a look at PHP Logging Libraries if you’re working on a custom stack or PHP Framework Logging if you’re using a framework like Laravel or Symfony. With the built-in error log, there are a few different elements you’ll want to keep in mind:
Configuration SettingsLet’s start by reviewing how the PHP engine can be configured to display and log error output. These settings are useful to review if you’re setting up a new server or trying to figure out if logging is configured on a server someone else has set up. Default ConfigurationBy default, the configuration pertaining to errors is found in the following directives within the configuration file php.ini. There may be several different php.ini files on your system depending on whether you’re running PHP on the command-line interface (CLI) or behind a web server such as Apache or NGINX. Here’s where you can find your php.ini file in common distributions of Linux. Default Configuration File LocationsCommon Configuration DirectivesYou can find a full list of directives on the PHP documentation site. Here are some of the more common directives relevant to logging. Notes: *Change to 0 for web-facing servers as a security measure. **If set to syslog, it will send errors to the system log. Run-Time ConfigurationPHP provides several functions for reading and modifying run-time configuration directives. These can be used in an application to override settings in php.ini. The ability to modify configuration values is useful when you don’t have access to the PHP configuration files (such as in a serverless environment), when troubleshooting an application, or when running certain tasks (such as a cron job requiring extra memory). You may need to look for calls to The two most common are as follows:
Default Error LogsWhen log_errors is enabled but error_log hasn’t been defined, errors are logged to the web server error log. The default locations for Apache and NGINX are as follows:
Logging FunctionsHere are functions used to facilitate application error logging. Understanding how logging works natively in PHP has value, but you should also look into using popular PHP logging libraries because of the functionality they add. This function sends a message to the currently configured error log. The most common usage is as follows:
On an Apache server, this will add a new line to
You can read more about logging in Apache in this guide. You can also send a message to a different file. However, this isn’t recommended, as it can lead to confusion.
You can use the This function takes two parameters—an error message string and an error level.
Another way of logging errors is to send them directly to the system using the
The above will log a new message to
PHP Log FormatWhen logging data, you have to make sure you follow a meaningful formatting convention, including fields such as date/time, filename, and message. This allows you to better analyze and search your data. You can also make it a separate function to handle log formatting. The same technique is used by the Monolog package.
You can check our Apache logging guide for more details about configuring your web server logging format. PHP Error Log TypesPHP provides a variety of error log types for identifying the severity of errors encountered when your application runs. The error levels indicate if the engine couldn’t parse and compile your PHP statements, if it couldn’t access or use a resource needed by your application, and even if you had a possible typo in a variable name. Although the error levels are integer values, there are predefined constants—such as E_ERROR and E_PARSE—for each one. Using the constants can make your code easier to read and understand and keep it forward-compatible when new error levels are introduced. Error-level constants are used by the error_reporting() function to indicate which types of errors should be displayed or logged. Note this can also be configured in the INI file. You can also use bitwise operators to customize the verbosity of your application logs.
A Note on Error SuppressionYou’ve probably encountered code that prefixes a function call with the @ symbol, which is the error control operator. This suppresses any errors emitted by the function. In the end, this means if the function fails, you won’t see any errors related to it on screen or in your logs. This is a poor practice and should be avoided. Remember, you can always set a custom error handler to catch errors.
If you’re trying to fix a bug but don’t see any errors, search your code for function calls prefixed with one @. You can also install and enable the scream extension, which disables this behavior and ensures all errors are reported. The best practice is to set the error level to Enabling the PHP Error LogLog messages can be generated manually by calling You can enable the error log in one of two ways: by editing Via
Via
This run-time setting is necessary only if the log_errors directive isn’t enabled as a general configuration for a particular reason and your application code requires it. As a best practice, you can enable error reporting and logging on web-facing servers and disable displaying errors in response. Displaying errors in response in a live environment can be a serious security mistake and must be avoided. The display_errors directive is mentioned in the following configuration due to this security concern. Custom Logging With JSONLogging user actions and activities provides a valuable source of information for seeing which features get used, for knowing the steps users take to accomplish tasks, and for tracking down and recreating errors they encounter. Though you can log this activity to a local file, you’ll typically want to log this to an existing logging service to make it easier to analyze and report. Instead of inventing your own format—which would require a custom parser—use JSON as your logging format. JSON is a structured format designed to make it easy for logging services and other applications to parse events. For more on getting the most out of JSON logging, see Eight Handy Tips to Consider When Logging in JSON. As a best practice, use JSON to log user behavior and application errors. You can do this from the beginning, so you don’t have to convert or lose older logs. PHP arrays and objects can be converted to a JSON string using This is an example of how to use the
This is an example of how to use the
ExceptionsExceptions are an elegant way to handle application errors and subsequent logging. They’re either thrown and caught within a Exceptions are used when parts of your application logic can’t continue the normal flow of execution. The Base ExceptionPHP has a base The following example assumes
The example above would produce the following error log entry:
A Custom ExceptionLet’s say you have a certain frequency of a specific type of error and would like to tailor a custom exception to handle it. In the following example, we’ll create a custom exception called Define the custom exception class:
Define a class to throw the custom exception:
Catch the user login attempt with the custom exception:
If we were to run a completed program, it would display an output similar to this:
SPL ExceptionsThe PHP has a built-in code library called Standard PHP Library (SPL). The library has a number of exception classes defined and available for common code-level errors. These exceptions extend from the base PHP exception class internally. They’re different in name only and can be thrown, caught, and logged. First, we can define a class to throw an SPL exception (
Attempt to use an undefined method:
PHP Throwable InterfacePHP 7 and 8 offer a Throwable interface (implemented by the Exception and Error classes) designed to catch internal PHP exceptions like TypeError and ParseError. In earlier versions, fatal errors couldn’t be handled gracefully because they immediately terminated program execution. You can find the full predefined exception documentation here. The Throwable interface can’t be implemented by custom exceptions directly and must extend from the base exception class for implementation. How to enable PHP error log in Apache?Here is how to activate this feature in four steps:. 01: Edit File php.ini: sudo nano /etc/php7/apache2/php.ini. ... . 02: Now create the log-file: sudo touch /var/log/php-errors.log.. 03: Change ownership to make the file accessible to the Apache user: sudo chown wwwrun /var/log/php-errors.log.. 04: Restart Apache:. How to set error log path in PHP?The location of the error log file itself can be set manually in the php. ini file. On a Windows server, in IIS, it may be something like "'error_log = C:\log_files\php_errors. log'" in Linux it may be a value of "'/var/log/php_errors.
How to use error log PHP?Enabling the PHP Error Log
Log messages can be generated manually by calling error_log() or automatically when notices, warnings, or errors come up during execution. By default, the error log in PHP is disabled. You can enable the error log in one of two ways: by editing php. ini or by using ini_set .
How to show all errors warnings in PHP?Adding these lines to your PHP code file is the quickest way to output all PHP errors and warnings: ini_set ('display_errors', 1); ini_set ('display_startup_errors', 1); error_reporting (E_ALL); The ini_set() function will attempt to override the PHP ini file's configuration.
|