PHP Logging and Error Debugging Techniques

This article explains how to use PHP's built‑in functions and custom helpers for logging program execution and debugging errors, covering error_log(), custom log functions, error_reporting settings, try‑catch exception handling, and a comprehensive example that combines logging with exception tracking.

php Courses
php Courses
php Courses
PHP Logging and Error Debugging Techniques

In daily PHP development, logging and error debugging are essential. By recording logs we can trace program execution and troubleshoot issues, while debugging helps locate and fix code errors. This article introduces how to use PHP functions for logging and error debugging, providing relevant code examples.

1. Logging

Logging records important information during program execution for later review and analysis. In PHP, built‑in logging functions can be used.

1. Using error_log() function

The error_log() function records error and exception information. It can write messages to a specified log file or send them to an email address.

Below is a simple example demonstrating how to use error_log() to write a log entry:

<?php
$msg = "This is a log message.";
$filename = "logs/log.txt";

error_log($msg, 3, $filename);
?>

In this example we define the log message $msg, specify the target log file $filename, and call error_log() to write the message to the file.

2. Using a custom function for logging

Besides the built‑in error_log(), you can create a custom function to meet specific logging requirements.

Here is an example of a custom logging function:

<?php
function writeLog($msg, $filename) {
    $timestamp = date('Y-m-d H:i:s');
    $log = "[{$timestamp}] {$msg}
";
    file_put_contents($filename, $log, FILE_APPEND);
}

$msg = "This is a log message.";
$filename = "logs/log.txt";

writeLog($msg, $filename);
?>

The writeLog() function receives a message and a file name, adds a timestamp using date(), formats the log entry, and appends it to the file with file_put_contents() using the FILE_APPEND flag.

2. Error Debugging and Tracing

During development you may encounter syntax errors, logic errors, and other issues. Proper debugging techniques help you quickly locate and fix these problems.

Using error_reporting() to set the error reporting level

In PHP you can control which errors are displayed with the error_reporting() function.

Example:

<?php
// Show all errors
error_reporting(E_ALL);

// Show all errors except notices
error_reporting(E_ALL & ~E_NOTICE);
?>

The first call sets the level to E_ALL, displaying every type of error. The second call excludes E_NOTICE by using the bitwise NOT operator.

Using try‑catch blocks to capture and handle exceptions

PHP supports try‑catch blocks for exception handling. When an exception occurs, execution jumps to the catch block where you can process the error.

Example:

<?php
try {
    $result = 10 / 0; // Triggers a warning/exception
} catch (Exception $e) {
    echo "An exception occurred: " . $e->getMessage();
}
?>

In the catch block the exception message is obtained with $e->getMessage() and can be logged or displayed as needed.

3. Comprehensive Example

The following example combines logging and exception handling to trace program execution:

<?php
function writeLog($msg, $filename) {
    $timestamp = date('Y-m-d H:i:s');
    $log = "[{$timestamp}] {$msg}
";
    file_put_contents($filename, $log, FILE_APPEND);
}

$errorLog = "logs/error_log.txt";

try {
    // Execute some code...
    
    // Log successful execution
    $logMsg = "Code execution completed successfully.";
    writeLog($logMsg, $errorLog);
    
    // Execute other code...
} catch (Exception $e) {
    // Log error information
    $errorMsg = "An exception occurred: " . $e->getMessage();
    writeLog($errorMsg, $errorLog);
}
?>

In this script we define a log file, run code inside a try block, log a success message, and in the catch block log the exception details using the same writeLog() function.

Conclusion

This article introduced how to use PHP functions for logging and error debugging. By recording logs you can trace program execution and investigate problems, while debugging techniques help you locate and fix code errors. The examples provided should assist you in implementing effective logging and debugging in your PHP projects.

PHP8 Video Tutorial

Scan the QR code to receive free learning materials

QR Code
QR Code
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception HandlingloggingPHPerror-debugging
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.