How to print log in PHP?

PHP Error Reference

Example

Send error messages to the web server's error log and to a mail account:

// 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, "[email protected]");
}
?>



Definition and Usage

The error_log() function sends an error message to a log, to a file, or to a mail account.


Syntax

error_log(message, type, destination, headers);

Parameter Values

ParameterDescriptionmessageRequired. Specifies the error message to logtypeOptional. Specifies where the error message should go. Possible values:
  • 0 - Default. Message is sent to PHP's system logger, using the OS' system logging mechanism or a file, depending on what the error_log configuration is set to in php.ini
  • 1 - Message is sent by email to the address in the destination parameter
  • 2 - No longer in use (only available in PHP 3)
  • 3 - Message is appended to the file specified in destination
  • 4 - Message is sent directly to the SAPI logging handler
destinationOptional. Specifies the destination of the error message. This value depends on the value of the type parameterheadersOptional. Only used if the type parameter is set to 1. Specifies additional headers, like From, Cc, and Bcc. Multiple headers should be separated with a CRLF (\r\n)

Technical Details

Return Value:TRUE on success. FALSE on failurePHP Version:4.0+Binary Safe:NoPHP Changelog:PHP 5.2.7: The value of 4 was added to the type parameter
PHP Error Reference

The echo command is used in PHP to print any value to the HTML document. Use <script> tag inside echo command to print to the console.

Syntax:

echo "This is GeeksforGeeks Tutorial.";
echo variable_name;

Note: The echo command will print the HTML document. This feature can be used to put JavaScript statements in the HTML page.

Example 1: This example illustrates how to use echo keyword to display content.




<?php 

  

// Declare variable and store the string

$var1 ="GeeksforGeeks";

$var2 =

GeeksforGeeks
A computer science portal
1;

  

GeeksforGeeks
A computer science portal
4

GeeksforGeeks
A computer science portal
5 $var1
GeeksforGeeks
A computer science portal
7
GeeksforGeeks
A computer science portal
8
GeeksforGeeks
A computer science portal
7$var2 ;

<?php 2

Output:

GeeksforGeeks
A computer science portal

Dot ‘.’ operator is used to joining two strings in PHP. You can print multiple variables by joining with a dot ‘.’ operator. The echo keyword is used to display the values of variables var1 and var2 to the HTML document which is readable by the browser normally. This property can be taken into an advantage in writing to JavaScript console using PHP. The JavaScript code can be written in the echo section and taken to the HTML document.

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.

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 your application triggers, usually caused by missing or incorrect user input
  3. Activities in your application you may want to analyze later, such as recording when a user account is updated or content in a content management system (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 someone else has set up.

Default Configuration

By 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 Locations

How to print log in PHP?

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.

How to print log in PHP?

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 Configuration

PHP 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 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 still don’t see the error output, chances are it’s being overridden somewhere.

The two most common are as follows:

  1. ini_get(string): Retrieves current directive setting
  2. ini_set(string, mixed): Sets a directive

Default Error Logs

When 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:

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

Logging Functions

Here 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:

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 isn’t recommended, as it can lead to confusion.

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

You can use the display_errors 0 error levels in your application to report errors with varying severity for logging. Like the core constants, there are levels for fatal errors (display_errors 1), warnings (display_errors 2), and notices (display_errors 3). In your code, use the display_errors 4 function for custom errors. If your code encounters an error, use display_errors 5with a descriptive message to let your error handler know something went wrong instead of using the display_errors 6 function to abruptly terminate everything.

This function takes two parameters—an error message string and an error level.

display_errors 7
display_errors 8
display_errors 9

ini_get(string)0

ini_get(string)1

ini_get(string)2
ini_get(string)3
ini_get(string)4
ini_get(string)5

Another way of logging errors is to send them directly to the system using the ini_get(string)6 function. It takes the error level as the first parameter (ini_get(string)7, ini_get(string)ini_get(string)9, ini_set(string, mixed)0, ini_set(string, mixed)1, ini_set(string, mixed)2, ini_set(string, mixed)3, ini_set(string, mixed)4); the second parameter is the actual error message.

ini_set(string, mixed)5
ini_set(string, mixed)6
ini_set(string, mixed)7

The above will log a new message to ini_set(string, mixed)8:

ini_set(string, mixed)9

PHP Log Format

When 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.

/var/log/apache2/error.log0
/var/log/apache2/error.log1
/var/log/apache2/error.log2
ini_get(string)3
/var/log/apache2/error.log4
/var/log/apache2/error.log5
ini_get(string)5

/var/log/apache2/error.log7

/var/log/apache2/error.log8
/var/log/apache2/error.log9

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, 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.

 /var/log/nginx/error.log0
 /var/log/nginx/error.log1

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 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.

 /var/log/nginx/error.log2
 /var/log/nginx/error.log3

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  /var/log/nginx/error.log4 unless a specific use case is required. Notices and warnings can indicate variables aren’t being created in the way you intended.

Enabling the PHP Error Log

Log messages can be generated manually by calling  /var/log/nginx/error.log5 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  /var/log/nginx/error.log6or by using /var/log/nginx/error.log7. Modifying  /var/log/nginx/error.log8i is the proper way to do this. Be sure to restart your web server after editing the configuration.

Via  /var/log/nginx/error.log9:

error_log('Your message here');0

Via ini_set():

error_log('Your message here');2

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 JSON

Logging 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 usingerror_log('Your message here');3. Likewise, JSON can be reconstituted as a native PHP construct by using error_log('Your message here');4.

This is an example of how to use the error_log('Your message here');5 function with an associative array:

error_log('Your message here');6
error_log('Your message here');7
error_log('Your message here');8
error_log('Your message here');9
/var/log/apache2/error.log0
/var/log/apache2/error.log1

/var/log/apache2/error.log2

/var/log/apache2/error.log3
/var/log/apache2/error.log4

This is an example of how to use the /var/log/apache2/error.log5function:

/var/log/apache2/error.log6
/var/log/apache2/error.log7
/var/log/apache2/error.log8
/var/log/apache2/error.log9
[16-Jul-2019 17:36:01 America/New_York] Your message here0
[16-Jul-2019 17:36:01 America/New_York] Your message here1
[16-Jul-2019 17:36:01 America/New_York] Your message here2
[16-Jul-2019 17:36:01 America/New_York] Your message here3

Exceptions

Exceptions are an elegant way to handle application errors and subsequent logging. They’re either thrown and caught within a [16-Jul-2019 17:36:01 America/New_York] Your message here4 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 [16-Jul-2019 17:36:01 America/New_York] Your message here5 class available by default in the language. The base exception class is extensible if required.

The following example assumes [16-Jul-2019 17:36:01 America/New_York] Your message here6.

[16-Jul-2019 17:36:01 America/New_York] Your message here7
[16-Jul-2019 17:36:01 America/New_York] Your message here8
[16-Jul-2019 17:36:01 America/New_York] Your message here9
ini_get(string)3
error_log('Invalid input on user login', 3, '/var/www/example.com/log/error.log');1
error_log('Invalid input on user login', 3, '/var/www/example.com/log/error.log');2
error_log('Invalid input on user login', 3, '/var/www/example.com/log/error.log');3
error_log('Invalid input on user login', 3, '/var/www/example.com/log/error.log');4

error_log('Invalid input on user login', 3, '/var/www/example.com/log/error.log');5
error_log('Invalid input on user login', 3, '/var/www/example.com/log/error.log');6

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

ini_get(string)5

The example above would produce the following error log entry:

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

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 display_errors 00 to handle incidences of too many login attempts.

Define the custom exception class:

display_errors 01

display_errors 02
display_errors 03
ini_get(string)3
ini_get(string)5

Define a class to throw the custom exception:

display_errors 06

display_errors 07
display_errors 08
display_errors 09
display_errors 10

display_errors 11
ini_get(string)3
ini_get(string)5

Catch the user login attempt with the custom exception:

display_errors 14
display_errors 15
display_errors 16
display_errors 17
display_errors 18
ini_get(string)5

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

display_errors 20

SPL Exceptions

The 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 (display_errors 21). The example uses the PHP magic methoddisplay_errors 22to catch an undefined method call.

display_errors 23
display_errors 24
display_errors 25
display_errors 26
display_errors 10

display_errors 28
ini_get(string)3
ini_get(string)5

Attempt to use an undefined method:

display_errors 14
display_errors 32
display_errors 33
display_errors 34
display_errors 35
display_errors 36
ini_get(string)5

PHP Throwable Interface

PHP 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 log print in PHP?

Logging in PHP can be accomplished in two ways:.
By writing to log files on the hard drive..
Using echo and var_dump to display variable values on web pages..

How to print error log in PHP?

Quickly Show All PHP Errors The quickest way to display all php errors and warnings is to add these lines to your PHP code file: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

How to write logs in PHP?

PHP's logging functions You can log any event you choose by explicitly calling PHP's error_log() or syslog() function within your code. These functions create logs containing the message string you provide. The syslog() function will use the configuration in your rsyslog. conf file to write log messages.

How to give a console log in PHP?

Using PHP libraries to console log.
If you want to keep it simple, use PHP json_encode function..
If you want to use more extensive features such as console.info, use PHPDebugConsole with PHPConsole as your backup..