How to Log Errors and Warnings into a File in PHP

In PHP, logging errors and warnings to files is essential for debugging and monitoring applications. PHP provides built-in functions like error_log() and ini_set() to capture and store error messages for later analysis.

Method 1 Using error_log() Function

The error_log() function sends error messages to the server's error log or a specified file ?

Syntax

error_log(string $message, int $messageType = 0, string $destination = '', string $extraHeaders = '');

Parameters

  • $message: The error message or data to be logged (string)

  • $messageType: (Optional) The type of message:

    • 0: Default message sent to PHP error log

    • 1: Message sent by email to specified destination

    • 3: Message appended to file specified in destination

  • $destination: (Optional) Email address or file path for types 1 and 3

  • $extraHeaders: (Optional) Additional headers for email (not used for file logging)

Example

<?php
// Enable error logging
ini_set('log_errors', 1);
ini_set('error_log', '/tmp/error.log');

// Log an error message to specific file
error_log("Database connection failed", 3, "/tmp/error.log");

// Log a warning message to specific file
error_log("User attempted invalid login", 3, "/tmp/error.log");

// Log to default PHP error log
error_log("This goes to default error log");
?>

Method 2 Using ini_set() Configuration

The ini_set() function modifies PHP configuration settings at runtime to control error logging behavior ?

Syntax

ini_set(string $option, mixed $value): mixed

Example

<?php
// Configure error reporting and logging
ini_set('error_reporting', E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', '/tmp/php_errors.log');

// Trigger custom errors for demonstration
trigger_error("This is a custom error message", E_USER_ERROR);
trigger_error("This is a custom warning message", E_USER_WARNING);

// Example of actual error that would be logged
$undefined_variable = $nonexistent_var; // Notice logged automatically
?>

Note: Ensure the log file path has proper write permissions for the web server user (e.g., www-data). You may need to create the log directory and set appropriate permissions using chmod 755.

Comparison of Methods

Aspect error_log() ini_set()
Manual logging Yes No
Automatic error capture No Yes
Custom messages Yes Via trigger_error()
File destination control Per message Global setting

Conclusion

Use error_log() for manual logging of specific events and ini_set() for automatic capture of all PHP errors. Both methods are essential for effective application monitoring and debugging in production environments.

Updated on: 2026-03-15T10:29:20+05:30

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements