How to Generate Custom error_log File in PHP

Updated on ... 28th August 2023

PHP offers various methods to work with PHP error logs, in which we can generate a manual error_log file and also automate it.

In this tutorial we we will discuss different approaches to generating error_log file, error_log(), file_put_contents(), and using php.ini

Note: Remember PHP gives lots of information about the php file path, database schema, and other sensitive information about the php file and database.  You are strongly advised to use error logging instead of error displaying on production websites.

Generate error_log using error_log() php function:

The PHP error_log() function can be used to generate error messages to a given file path. The first argument of this function is the error message to be generated. The second argument tells where to generate/log the error message. In this case, I am using the second argument   3 to redirect the error message to a file. The third argument is used to define the file path of the error_log file.


                                                    

                                                    

                                                    <?php
date_default_timezone_set('Asia/Kolkata');
$server = "localhost";
$user = "root";
$password  = "";
$database = "mysqli_prepared_crud2";

try {
    $conn = new mysqli($server, $user, $password, $database);

    if ($conn->connect_error) {
        throw new Exception($conn->connect_error);
    }

    // ... Perform database operations here ...

    $conn->close();
} catch (Exception $e) {
    // //Generate a log entry with date, time, and file path
    $errorLog = "[" . date('Y-m-d H:i:s') . "] Error in " . __FILE__ . ": " . $e->getMessage() . "\n";

    error_log($errorLog, 3, 'custom_error_log.txt');

    // Display a user-friendly error message (optional)
    echo "An error occurred. Please try again later.";
}

                                                    

                                                

Generate error_log using file_put_contents() PHP function:

The PHP file_put_contents() function is used to write any text data to a file. It can generate a new file if it doesn't exist and can also append data to an existing file that already exists. 

file_put_contents() function takes three parameters: 

  1. The first parameter defines the name of the file or file path where the data will be written or appended. 
  2. The second parameter holds the actual data that you want to write to the file.
  3. The third parameter defines optional flags that modify the behavior of the function. One common flag is FILE_APPEND, which, when used, appends the data to the end of the file rather than overwriting its contents



                                                    

                                                    

                                                    <?php
date_default_timezone_set('Asia/Kolkata');
$server = "localhost";
$user = "root";
$password  = "";
$database = "mysqli_prepared_crud2";

try {
    $conn = new mysqli($server, $user, $password, $database);

    if ($conn->connect_error) {
        throw new Exception($conn->connect_error);
    }

    // ... Perform database operations here ...

    $conn->close();
} catch (Exception $e) {
    // // Generate a log entry with date, time, 
    //$errorLog = "[" . date('Y-m-d H:i:s') . "] Error: " . $e->getMessage() . "\n";
    // //Generate a log entry with date, time, and file path
    $errorLog = "[" . date('Y-m-d H:i:s') . "] Error in " . __FILE__ . ": " . $e->getMessage() . "\n";

    file_put_contents('custom_error_log.txt', $errorLog, FILE_APPEND);

    // Display a user-friendly error message (optional)
    echo "An error occurred. Please try again later.";
}

                                                    

                                                

You Should Also Read

 Generate error_log by changing in php.ini

We can add the following lines directly to php.ini to make the configuration changes permanent for every PHP script that generates error logs and warnings.


                                                    

                                                    

                                                    log_errors = on
error_log = ./errors_log_file_path

                                                    

                                                

Let's see another example where we will use php different types.

while using php procedural way:


                                                    

                                                    

                                                    <?php
date_default_timezone_set('Asia/Kolkata');
$server = "localhost";
$user = "root";
$password  = "";
$database = "mysqli_prepared_crud2";

try {
    $conn = mysqli_connect($server, $user, $password, $database);

    if (!$conn) {
        throw new Exception("Connection failed: " . mysqli_connect_error());
    }

    $query = "SELECT * FROM your_table_name";
    $result = mysqli_query($conn, $query);

    if (!$result) {
        throw new Exception("Query failed: " . mysqli_error($conn));
    }

    // Fetch and process the data...

    mysqli_close($conn);
} catch (Exception $e) {
    // Generate a log entry with date, time, file path, query, and error message
    $errorLog = "[" . date('Y-m-d H:i:s') . "] Error in " . __FILE__ . " (Query: $query): " . $e->getMessage() . "\n";

    // Append the log entry to the log file
    file_put_contents('custom_error_log.txt', $errorLog, FILE_APPEND);

    // Display a user-friendly error message (optional)
    echo "An error occurred. Please try again later.";
}

                                                    

                                                

while using php PDO:


                                                    

                                                    

                                                    <?php
date_default_timezone_set('Asia/Kolkata');
$server = "localhost";
$user = "root";
$password = "";
$database = "pdo_prepared_crud";

try {
    $conn = new PDO("mysql:host=$server;dbname=$database", $user, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $query = "SELECT * FROM your_table_name";
    $result = $conn->query($query);

    if (!$result) {
        throw new Exception("Query failed: " . $conn->errorInfo()[2]);
    }

    // Fetch and process the data...

} catch (Exception $e) {
    // Generate a log entry with date, time, file path, query, and error message
    $errorLog = "[" . date('Y-m-d H:i:s') . "] Error in " . __FILE__ . " (Query: $query): " . $e->getMessage() . "\n";

    // Append the log entry to the log file
    file_put_contents('custom_error_log.txt', $errorLog, FILE_APPEND);

    // Display a user-friendly error message (optional)
    echo "An error occurred. Please try again later.";
}
?>

                                                    

                                                

Related Post

Leave a comment