Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Exceptions and Errors

PHP error_log() function

Reference for PHP error_log(): write messages to the server log, a file, stderr or email, the message types, the error_log setting and logging best practices.

error_log() sends a message to PHP's error log. Where the message ends up depends on the error_log ini setting and the message type you pass: the web server's log, a file, standard error in the CLI, or an email. It is the simplest way to record what happened without showing it to the visitor.

Real applications usually use a logging library (Monolog, PSR-3), but error_log() is what those libraries often use underneath and it is always available.

PHP
error_log("Payment failed for order 1042");
error_log("Saved\n", 3, "/tmp/app.log");

Try it

PHP Logging to a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Logging exceptions with context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
error_log(
    string $message,
    int $message_type = 0,
    ?string $destination = null,
    ?string $additional_headers = null
): bool
Name Description
$message The text to log.
$message_type 0 (default): the system logger or the file named by the error_log ini setting. 1: email to $destination. 3: append to the file $destination. 4: send straight to the SAPI logger.
$destination Email address (type 1) or file path (type 3).
$additional_headers Extra mail headers for type 1.

Return value: true on success, false on failure.

Usage notes

  • Type 3 adds no newline or timestamp. You write "\n" yourself. Types 0 and 4 add a timestamp when they write to a file.
  • Where type 0 goes: the error_log setting if set; otherwise the web server's error log; in the CLI, standard error.
  • Type 1 needs a mail setup (sendmail). It is rarely used now; use a monitoring service.
  • Don't log secrets: passwords, tokens, card numbers and full request bodies.
  • One line per event makes logs searchable. Encoding context as JSON works well.
  • Multi-line messages (such as stack traces) become several log entries in some setups; collapse or encode them.
  • Not a replacement for handling. Logging a failure does not recover from it. Log in your exception handler and then respond properly.
  • Logging is controlled separately from display: log_errors decides whether PHP's own warnings are logged; error_log() always writes.
  • File permissions: the PHP process must be able to write to the path.