Menu Close

Create PHP custom error log file

In web development, debugging is an essential part of the process. Logging errors and exceptions is a common practice to identify and troubleshoot issues within your PHP applications. In this article, we will guide you on how to create a custom PHP error log file using a simple function.

Why Use a Custom Error Log File?

The ability to store error messages in a custom log file allows you to centralize and manage error information more effectively. This is especially useful in production environments where you want to monitor and address errors without exposing sensitive information to end-users.

Creating the PHP Error Logging Function

Here’s a PHP function that logs error messages to a custom error log file:

function logErrorMessage($errorMessage) {
    // error log file name
    $errorLogFileName = dirname( __FILE__ ).'/error-log.txt';

    // Write the error message
    $logMessage = date('Y-m-d H:i:s') . ' - ' . $errorMessage . PHP_EOL;

    if (file_put_contents($errorLogFileName, $logMessage, FILE_APPEND | LOCK_EX) !== false) {
        return "Message was written to " . $errorLogFileName;
    } else {
        return "Failed write a message";
    }
}

 

How the Function Works

The logErrorMessage function accepts an error message as its parameter.

It specifies the location and name of the error log file. In this example, the log file is named “error-log.txt” and is placed in the same directory as the script using dirname(__FILE__).

The function creates a log message that includes the current date and time, as well as the provided error message.

It then appends the log message to the error log file using file_put_contents. The FILE_APPEND flag ensures that the message is added to the end of the file, while LOCK_EX provides exclusive file locking to prevent concurrency issues.

The function returns a message indicating whether the logging was successful or not.

Using the logErrorMessage Function

To log an error message using this function, you simply call it with the error message you want to log. For example:

$errorMessage = 'this error message is written to custom error log file';
logErrorMessage($errorMessage);

 

Conclusion

Creating a custom PHP error log file is a practical way to maintain and manage error messages in your web applications. It allows you to keep a record of errors, enabling you to identify and resolve issues efficiently. By implementing the logErrorMessage function, you can easily integrate error logging into your PHP projects.

Leave a Reply

Your email address will not be published. Required fields are marked *