1. <track id="yv6cu"><div id="yv6cu"></div></track>

        <track id="yv6cu"><span id="yv6cu"></span></track>
        <nobr id="yv6cu"></nobr><menuitem id="yv6cu"><dfn id="yv6cu"></dfn></menuitem>

        Ultimate Guide to Logging

        Your open-source resource for understanding, analyzing, and troubleshooting system logs

        PHP Logging Basics

        This guide explores the basics of logging in PHP including how to configure logging, where logs are located, and how logging can help you to be more effective with troubleshooting and monitoring your PHP applications.

        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:

        1. Errors emitted by the PHP engine itself when a core function fails or if code can’t be parsed
        2. Custom errors that your application triggers, usually caused by missing or incorrect user input
        3. Activities in your application that you may want to analyze at a later time, such as recording when a user account is updated or content in a CMS is updated

        Configuration Settings

        Let’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 that someone else has setup.

        Default Configuration

        By default, the configuration pertaining to errors is found in the following directives within the configuration file php.ini. There might be several different php.ini files on your system depending on how you’re running PHP, whether it’s on the 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 Locations

        Operating System Path Type
        Debian-Based (Debian, Ubuntu, Linux Mint, etc.) /etc/php/7.3/apache2/php.ini Apache Module
        Redhat / Fedora / CentOS /etc/php.ini All Versions
        OpenSUSE /etc/php/7.3/apache2/php.ini Apache Module

        Common Configuration Directives

        You can find a full list of directives on the PHP documentation site. Here are some of the more common directives relevant to logging.

        Directive Default Recommended Description
        display_errors ** 1 0 Defines whether errors are included in output.
        display_startup_errors 0 0 Whether to display PHP startup sequence errors.
        error_log *** 0 path Path to the error log file. When running PHP in a Docker container, consider logging to stdout instead.
        error_reporting null E_ALL The minimum error reporting level.
        log_errors 0 1 Toggles error logging.
        log_errors_max_length 1024 1024 Max length of logged errors. Set to zero for no maximum.
        report_memleaks 1 0 Reports memory leaks detected by Zend memory manager.
        track_errors 0 1 Stores the last error message in $php_errormsg.

        Notes:

        • ** Change to 0 for web-facing servers as a security measure.
        • *** If set to syslog, will send errors to the system log.

        Run-Time Configuration

        PHP provides a number of 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 PHP’s configuration files (such as a serverless environment), when troubleshooting an application, or when running certain tasks (such as a cron job that requires extra memory). You may need to look for calls to ini_set() in your code if the application isn’t behaving as expected. For example, if you set display_errors to 1 in php.ini, but you still don’t see error output, chances are it’s being overridden somewhere.

        The two most common are:

        ini_get(string <directive name>)

        Retrieves current directive setting.

        $displayErrors = ini_get(‘display_errors’);
        
        $errorLogPath = ini_get(‘error_log’);

        ini_set(string <directive name>, mixed <setting>)

        Sets a directive.

        ini_set(‘display_errors’, false);
        
        ini_set(‘error_log’, ‘/tmp/php.log’);

        Default Error Logs

        When log_errors is enabled but error_log has not been defined—errors are logged to the webserver error log.? The default location for Apache and Nginx follow. Consult your webserver configuration which may have been changed from the default.

        • Apache: /var/log/apache2/error.log
        • Nginx: /var/log/nginx/error.log

        Logging Functions

        Here are functions used to facilitate application error logging. The following table lists PHP functions related to logging, with a few examples following. Understanding how logging works natively in PHP most certainly has value, but you should also look into using popular PHP logging libraries because of the functionality they add.

        error_log()

        This function sends a message to the currently configured error log; the most common use is:

        error_log(‘Your message here’);

        On an Apache server this will add a new line to /var/log/apache2/error.log.

        [16-Jul-2019 17:36:01 America/New_York] Your message here

        You can read more about logging in Apache in this guide.

        You can also send a message to a different file however this is not recommended as it can lead to confusion.

        error_log(‘Invalid input on user login’, 3, ‘/var/www/example.com/log/error.log’);

        trigger_error()

        You can use the E_USER_* error levels in your application to report errors with varying severity for logging. Like the core constants, there are levels for fatal errors (E_USER_ERROR), warnings (E_USER_WARNING), and notices (E_USER_NOTICE). In your code, use the trigger_error() function for custom errors. If your code does encounter an error, use trigger_error() with a descriptive message to let your error handler know that something went wrong instead of using the die() function to abruptly terminate everything.

        This function takes two parameters, an error message string and an error level, as you can see below.

        function foo($email) {
        
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        
        trigger_error('Supplied value is not a valid email', E_USER_WARNING);
        
        return;
        
        }
        
        // rest of function continues
        
        }

        syslog()

        Another way of logging errors is to send them directly to the system using the syslog() function. It takes the error level as the first parameter (LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG); the second parameter is the actual error message.

        Example (using openlog() for the connection):

        openlog('CrawlerApp', LOG_CONS | LOG_NDELAY | LOG_PID, LOG_USER | LOG_PERROR);
        
        syslog(LOG_WARNING, "User #14 is logged from two different places.");
        
        closelog();

        The above will log a new message to /var/log/syslog:

        Aug 3 10:45:15 vaprobash php: User #14 is logged from two different locations.

        PHP Log Format

        When logging data, you have to make sure you follow a meaningful formatting convention, including fields such as date/time, filename, message, etc. 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.

        function logger($message, array $data, $logFile = "error.log"){
        
        foreach ($data as $key => $val) {
        
        $message = str_replace("%{$key}%", $val, $message);
        
        }
        
        ?
        
        $message .= PHP_EOL;
        
        ?
        
        return file_put_contents($logFile, $message, FILE_APPEND);
        
        }
        
        ?
        
        logger("%file% %level% %message%", ["level" => "warning", "message" =>"This is a message", "file" =>__FILE__]);
        
        ?
        
        // error.log
        
        /var/www/html/test.php warning This is a message

        You can check our Apache logging guide for more details about configuring your web server logging format.

        PHP Error Log Types

        PHP 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, or couldn’t access or use a resource needed by your application, all the way down to letting you know if you have a possible typo in a variable name.

        Although the error levels are integer values, there are predefined constants for each one. Using the constants will make your code easier to read and understand and keep it forward-compatible when new error levels are introduced. Common error levels encountered include:

        • E_ERROR – These are fatal run-time errors that halt script execution, such as running out of memory or calling a function that does not exist.
        • E_WARNING – A run-time warning is an error that does not halt script execution but can cause your code to not work as expected. For example, fopen() will return false and trigger an E_WARNING if you try to open a file that does not exist. The rest of your code won’t be able to read or write to the requested file.
        • E_PARSE – These are compile-time parse errors, like missing parentheses or semicolons.
        • E_NOTICE – Notices indicate possible bugs, such as using a variable that doesn’t exist in an expression. This could mean the variable name has a typo or needs to be assigned some value earlier.
        • E_STRICT – These errors indicate places in your code that may stop working in future versions of PHP. Using mysql_query() will trigger a strict error because the extension that provides that function is deprecated, and in fact is not bundled in PHP 7.

        Error-level constants are used by the error_reporting() function to indicate which types of errors should be displayed or logged. Note that this can also be configured in the INI file. You can also use bitwise operators to customize the verbosity of your application logs.

        // report all errors except notices and strict errors
        
        error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);

        A Note on Error Suppression

        You’ve probably encountered code that prefixes a function call with the @ symbol, which is the error control operator. This suppresses any errors emitted by that function. In the end, this means that 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.

        // Please don’t do this.
        
        $fh = @fopen(‘example.csv’, ‘r’);

        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.

        Best practice—set the error level to E_ALL unless a specific use case is required. Notices and warnings can indicate variables aren’t being created in the way you were thinking.

        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. Modifying php.ini is the proper way to do this. Be sure to restart your web server after editing the configuration.

        Via php.ini:

        log_errors = 1

        Via ini_set():

        ini_set(‘log_errors’, 1);

        This run-time setting is necessary only if the log_errors directive is not enabled as a general configuration for a particular reason, and your application code requires it.

        Best practice—be sure to enable error reporting and logging on web-facing servers and disable displaying errors in response. Displaying errors in response on a live environment is 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 JSON

        Logging user actions and activities provides a valuable source of information for seeing which features get used, the steps users take to accomplish tasks, and for tracking down and recreating errors that they encounter. While you can log this activity to a local file, typically you’ll want to log this to an existing logging service to make it easier to analyze and report. Instead of inventing your own format—that would require a custom parser—use JSON as your logging format. JSON is a structured format that makes it easy for logging services and other applications to parse events. For more on getting the most out of JSON logging, see 8 Handy Tips to Consider When Logging in JSON.

        Best practice—use JSON to log user behavior and application errors. Do this from the beginning so you don’t have to convert or lose older logs.

        PHP arrays and objects can be converted to JSON string using json_encode(). Likewise, JSON can be reconstituted as a native PHP construct by using json_decode(). A few code examples follow that demonstrate the functions first, then using them to log and parse an entry.

        Example: Using the json_encode() function with an associative array

        $logdata = [
        
        'msg' => 'Invalid username',
        
        'code' => '601',
        
        'url' => $_SERVER['REQUEST_URI'],
        
        'username' => 'ae2ivz!',
        
        ];
        
        ?
        
        $json = json_encode($logdata);
        
        ?
        
        // Produces:
        
        // {"msg":"Invalid username","code":"601","url":"http://example.com/foo","username":"ae2ivz!"}

        Example: Using the json_decode() function

        $jsonLogData = '{
        
        "msg":????? "Invalid username",
        
        "code":???? "601",
        
        "url":????? "http://example.com/foo",
        
        "username": "ae2ivz!"
        
        }';
        
        ?
        
        $logdata = json_decode($jsonLogData); // Convert to stdClass object.
        
        $logdata = json_decode($jsonLogData, true); // Convert to associative array.

        Exceptions

        Exceptions are an elegant way to handle application errors and subsequent logging. They are either thrown and caught within a try/catch/finally block, or handled by a custom exception function.

        Exceptions are used when parts of your application logic can’t continue the normal flow of execution.

        The Base Exception

        PHP has a base Exception class that is available by default in the language. The base Exception class is extensible if required.

        Example: (assumes directive log_errors = 1)

        try{
        
        if(true){
        
        throw new Exception("Something failed", 900);
        
        }
        
        } catch (Exception $e) {
        
        $datetime = new DateTime();
        
        $datetime->setTimezone(new DateTimeZone('UTC'));
        
        $logEntry = $datetime->format('Y/m/d H:i:s') . ‘ ‘ . $e;
        
        ?
        
        // log to default error_log destination
        
        error_log($logEntry);
        
        //Email or notice someone
        
        }

        The example above would produce the following error log entry:

        2015/07/30 17:20:02/Something failed/900//var/www/html/index.php/4

        A Custom Exception

        Let’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 TooManyLoginAttemptsException to handle incidences of too many login attempts.

        Define the custom exception class:

        class TooManyLoginAttemptsException extends Exception
        
        {
        
        public function __construct($msg, $code){
        
        parent::__construct($msg, $code);
        
        }
        
        }

        Define a class to throw the custom exception:

        class User
        
        {
        
        public function login(array $credentials)
        
        {
        
        if ($this->attempts($credentials) >= 10) {
        
        throw new TooManyLoginAttemptsException("Too many logging attempts from user {$credentials['email']} at {time()}");
        
        }
        
        // attempt login
        
        }
        
        }

        Code attempt to log in a user catching the custom exception:

        try {
        
        User::login($credentials);
        
        } catch (TooManyLoginAttemptsException $ex) {
        
        // You can add details to your logs here.
        
        error_log("Too many login attempts from user {$credentials['email']} at {“.time().”}");
        
        }

        If we were to run a completed program, it would display output similar to this:

        [Tue Jul 16 10:41:35 2019] Too many login attempts from user user@example.com at {1563288095}

        SPL Exceptions

        The PHP has a built-in code library called “Standard PHP Library” or 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 are different by name only, and can be thrown, caught, and logged.

        Define a class to throw an SPL exception: (BadMethodCallException)

        The example uses the PHP magic method __call() to catch an undefined method call.

        class Adapter{
        
        public function __call($method, $options){
        
        if (!method_exists($this, $method)) {
        
        throw new BadMethodCallException("Unknown method '{$method}'");
        
        }
        
        //code...
        
        }
        
        }

        Code attempt to use an undefined method:

        try {

        $adapter = new Adapter();

        $adapter->getConfig();

        } catch (BadMethodCallException $e) {

        // Log the error.

        error_log($e->getMessage());

        }

        PHP 7 Exceptions Changes

        In PHP 7, The exception hierarchy has changed in the core. A “Throwable” interface is introduced, and the Exception and Error classes implement it. This provides the ability to catch PHP internal exceptions, like TypeError, ParseError, etc. Up through PHP 5, fatal errors cannot be handled gracefully since they immediately terminate program execution. Full documentation is listed here.

        The Throwable interface cannot be implemented by custom exceptions directly and must extend from the base Exception class for implementation.

        Code attempt catches Throwable type hint:

        try {
        
        // Your code here
        
        } catch(Throwable $ex) {
        
        // You can catch any user or internal PHP exceptions
        
        }
        奇米影视盒