How do I log errors and warnings into a file?
You can configure PHP to capture all error and warning messages directly within your script using the error_log function, without touching php.ini. This approach is ideal for temporary scripts, one-off debugging tasks, or specific environments where you need dynamic logging paths that change per request. The core mechanism relies on manipulating the error reporting level and directing output to a designated file path.
First, you must ensure PHP is actually generating the messages you want to see. By default, many production servers suppress warnings and notices. To catch them inside your script, set the error reporting level to E_ALL before any output occurs. This flag tells PHP to report all types of errors, including those that might otherwise be ignored.
error_reporting(E_ALL);
ini_set('display_errors', 0); // Optional: Prevent printing to screen in production
Once the reporting level is set, you need to define where the logs should go. The error_log function accepts a path as its primary argument. You can pass an absolute filesystem path to ensure the log file lands exactly where you expect it, regardless of your script's current working directory. It is best practice to use dirname(__DIR__) or similar constructs to build a relative path that remains stable even if the application root changes.
$logPath = __DIR__ . '/logs/app_error.log';
error_log($message, 3, $logPath);
The second argument in the function call controls the output method. Passing 0 (or omitting it) sends logs to the standard error stream, which is usually captured by your web server's access/error logs. Passing 1 outputs directly to the browser. Passing 2 writes to the system log via syslog. Finally, passing 3 tells PHP to open the specific file you provided in the third argument and write exclusively to that file. This is the crucial step for isolating error logs from other system noise.
You can also control the format of the log entries using the fourth argument. By default, PHP includes a timestamp and the message content. You might want to append additional context, such as the script name or a custom identifier, directly into the string passed to error_log. For instance, you could create a helper function that prepends the current file and line number automatically:
function logError(string $message): void {
$logPath = __DIR__ . '/logs/errors.log';
// Prepend context to every error
$context = sprintf('[%s:%d] %s', basename($_SERVER['SCRIPT_FILENAME']), debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]['line'] ?? 0, $message);
error_log($context, 3, $logPath);
}
// Trigger an error to test
if (false === true) {
logError("Failed to load configuration");
}
A significant trade-off with this method is performance and scalability. Every time you call error_log, PHP performs a write operation on the disk. In high-traffic applications, excessive logging can slow down response times or fill up disk space rapidly if not managed correctly. If you are building a long-running web application, relying solely on error_log with file mode 3 might not be sufficient for production monitoring; instead, consider integrating with external log management tools like Laravel's built-in logging stack or using the Monolog library, which offers features like log rotation and multiple handlers.
Another pitfall is file permissions. Even if your code successfully opens the file path, the web server user (often www-data, apache, or nginx) must have write permissions for that directory. If the script runs in a container, ensure the volume mount includes the correct permission bits (chmod 775 or similar) so the application can append to the log file without triggering a "Permission denied" error.
Finally, remember that clearing the log requires deleting the file or truncating it manually. Unlike database tables where you might run a TRUNCATE, PHP does not automatically manage log file lifecycle. If your script runs repeatedly, the log file will grow indefinitely unless you implement a rotation strategy using tools like logrotate. For simple scripts, this manual management is acceptable, but for persistent services, automation is essential to prevent disk space exhaustion.