Open In App

How to Log Errors and Warnings into a File in PHP?

Last Updated : 19 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In PHP, errors and warnings can be logged into a file by using a PHP script and changing the configuration of the php.ini file. Two such approaches are mentioned below:

Approach 1: Using error_log() Function

The error_log() function can be used to send error messages to a given file. The first argument to the function is the error message to be sent. The second argument tells where to send/log the error message. In this case, the second argument is set to 3, used to redirect the error message to a file. The third argument is used to specify the file path of the error logging file.

Example: In this example, The PHP code logs an error message “This is an error message!” into a specified file “my-errors.log” using the error_log function with custom file path parameters.

<?php

// php code for logging error into a given file

// error message to be logged
$error_message = "This is an error message!";

// path of the log file where errors need to be logged
$log_file = "./my-errors.log";

// logging error message to given log file
error_log($error_message, 3, $log_file);

?>

Output:

[20-Dec-2018 17:32:00 UTC] This is an error message!

Approach 2: Using init_set() Function

  • The init_set() function allows a user to programmatically update configuration of the php.ini file.
  • The ini_set(“log_errors”, TRUE) command can be added to the PHP script to enable error logging in php.
  • The ini_set(‘error_log’, $log_file) command can be added to the PHP script to set the error logging file.
  • Further error_log($error_message) function call can be used to log error messages to the given file.

Example: In this example, The PHP code log an error message “This is an error message!” into a specified file “my-errors.log” by setting error logging parameters using ini_set and then calling error_log.

<?php
// PHP code for logging error into a given file

// error message to be logged
$error_message = "This is an error message!";

// path of the log file where errors need to be logged
$log_file = "./my-errors.log";

// setting error logging to be active
ini_set("log_errors", TRUE); 

// setting the logging file in php.ini
ini_set('error_log', $log_file);

// logging the error
error_log($error_message);

?>

Output:

[20-Dec-2018 17:30:35 UTC] This is an error message!

Similar Approach:

Following lines can also be added directly to php.ini to make the configuration changes permanent for every php script that logs errors and warnings.

log_errors = on
error_log = ./errors.log

Note: This approach is not highly reliable as compared to other approaches. Its better to use approach 1 as it gives flexibility of choosing different files for logging at same time without changing configuration of php.ini file.


Next Article

Similar Reads

three90RightbarBannerImg