error_log()

PHP's built-in logging function. Immediately available without external dependencies, supports output to files, system logs, email, etc. Suitable for simple string-based log output, but limited in structured logging and advanced features.

Logging LibraryPHPBuilt-in FunctionDebuggingSimpleStandard Feature

Library

error_log()

Overview

error_log() is PHP's built-in logging function that provides immediate availability without external dependencies as the simplest log output method widely used by PHP developers. Supporting flexible log output to system logs, files, email, and other destinations, it's optimal for small-scale scripts, quick debugging, and learning purposes. While production environments have functional limitations, it remains an essential tool for basic debugging and troubleshooting as the first step for PHP developers.

Details

error_log() continues to serve as a fundamental logging method in PHP development in 2025. Supporting four output destination types (system log, email, file, direct output) to accommodate diverse use cases, it provides immediate availability without additional configuration. Simple string-based message output enables rapid issue identification during debugging and error tracking. For full-scale web applications, advanced log management features (log levels, rotation, structured logging, etc.) are limited, leading to a trend toward migration to dedicated libraries like Monolog.

Key Features

  • Zero Configuration: No additional installation or setup required as PHP standard function
  • Multiple Output Destinations: Support for system logs, files, email, and SAPI output
  • Immediate Availability: Can be called instantly in any PHP script
  • Lightweight: Minimal overhead with no performance impact
  • Cross-Platform: Consistent operation across Unix/Linux and Windows environments
  • Debug Support: Real-time monitoring through integration with tail command

Pros and Cons

Pros

  • Immediate start without configuration as PHP standard function
  • Lightweight and simple implementation without external dependencies
  • Low learning curve, easily usable even for beginners
  • Quick issue identification during debugging and troubleshooting
  • Centralized monitoring through integration with system logs and management tools
  • Cross-platform support with low environment dependency

Cons

  • No concept of log levels (INFO, WARNING, ERROR, etc.)
  • Manual implementation required for structured logging (JSON, XML, etc.)
  • No log rotation or archiving functionality
  • Limited simultaneous output to multiple files and filtering capabilities
  • Performance optimization difficult during high-volume log output
  • Lack of enterprise-level advanced log management and analysis features

Reference Pages

Usage Examples

Installation and Basic Setup

<?php
// error_log() requires no additional installation as a PHP standard function
// Check and adjust log settings in php.ini (recommended)

// Basic log configuration check
echo "error_reporting: " . error_reporting() . "\n";
echo "log_errors: " . ini_get('log_errors') . "\n";
echo "error_log: " . ini_get('error_log') . "\n";

// Recommended production settings
ini_set('display_errors', 0);  // Disable error screen display
ini_set('log_errors', 1);      // Enable log recording
ini_set('error_log', '/var/log/php/php_errors.log');  // Specify log file

// error_log() basic syntax
// bool error_log(string $message, int $message_type = 0, ?string $destination = null, ?string $additional_headers = null)

// Simplest log output (to system log)
error_log("Application started");
?>

Basic Log Output (System Log/File/Email)

<?php
// 1. Output to system log (default, message_type = 0)
error_log("Database connection error occurred");
error_log("User authentication failed: " . $username);

// 2. Output to specified file (message_type = 3)
$logFile = '/var/log/myapp/application.log';
error_log("Custom log message", 3, $logFile);
error_log("Processing time: " . $processingTime . " seconds", 3, $logFile);

// 3. Log via email sending (message_type = 1)
$adminEmail = '[email protected]';
$criticalError = "CRITICAL: Server disk space shortage - Remaining: 5%";
error_log($criticalError, 1, $adminEmail);

// 4. Direct output to SAPI (Server API) (message_type = 4)
// Usually outputs to Apache error log, etc.
error_log("SAPI direct output test", 4);

// Timestamped log implementation example
function logWithTimestamp($message, $logFile = null) {
    $timestamp = date('Y-m-d H:i:s');
    $formattedMessage = "[$timestamp] $message";
    
    if ($logFile) {
        error_log($formattedMessage, 3, $logFile);
    } else {
        error_log($formattedMessage);
    }
}

// Usage examples
logWithTimestamp("User login: " . $userId);
logWithTimestamp("API call failed: " . $apiEndpoint, '/var/log/api_errors.log');

// Log with context information
function logWithContext($message, $context = [], $logFile = null) {
    $contextStr = empty($context) ? '' : ' | Context: ' . json_encode($context);
    $fullMessage = $message . $contextStr;
    
    if ($logFile) {
        error_log($fullMessage, 3, $logFile);
    } else {
        error_log($fullMessage);
    }
}

// Usage example
logWithContext(
    "Payment processing error", 
    [
        'user_id' => $userId,
        'amount' => $amount,
        'payment_method' => $paymentMethod
    ],
    '/var/log/payment_errors.log'
);
?>

Error Handling and Debug Practices

<?php
// Utilize error_log() with custom error handler
function customErrorHandler($severity, $message, $filename, $lineno) {
    $errorTypes = [
        E_ERROR => 'ERROR',
        E_WARNING => 'WARNING', 
        E_NOTICE => 'NOTICE',
        E_USER_ERROR => 'USER_ERROR',
        E_USER_WARNING => 'USER_WARNING',
        E_USER_NOTICE => 'USER_NOTICE'
    ];
    
    $errorType = $errorTypes[$severity] ?? 'UNKNOWN';
    $logMessage = sprintf(
        "%s: %s in %s on line %d",
        $errorType,
        $message,
        $filename,
        $lineno
    );
    
    error_log($logMessage, 3, '/var/log/php/custom_errors.log');
    
    // Continue processing in production, stop in development
    if (defined('ENVIRONMENT') && ENVIRONMENT === 'production') {
        return true;  // Continue error processing
    }
    return false;  // Delegate to default error handler
}

// Set custom error handler
set_error_handler('customErrorHandler');

// Combination with exception handler
function logException($exception) {
    $message = sprintf(
        "Uncaught %s: %s in %s:%d\nStack trace:\n%s",
        get_class($exception),
        $exception->getMessage(),
        $exception->getFile(),
        $exception->getLine(),
        $exception->getTraceAsString()
    );
    
    error_log($message, 3, '/var/log/php/exceptions.log');
}

set_exception_handler('logException');

// Debug logging function
function debugLog($variable, $label = 'DEBUG', $logFile = '/tmp/debug.log') {
    $output = "[$label] " . date('Y-m-d H:i:s') . " | ";
    
    if (is_array($variable) || is_object($variable)) {
        $output .= print_r($variable, true);
    } else {
        $output .= var_export($variable, true);
    }
    
    error_log($output, 3, $logFile);
}

// Usage example
$userData = ['id' => 123, 'name' => 'John Doe', 'email' => '[email protected]'];
debugLog($userData, 'USER_DATA');

// Performance measurement log
function measureAndLog($callback, $operationName, $logFile = '/var/log/performance.log') {
    $startTime = microtime(true);
    $startMemory = memory_get_usage();
    
    try {
        $result = $callback();
        $success = true;
        $error = null;
    } catch (Exception $e) {
        $result = null;
        $success = false;
        $error = $e->getMessage();
    }
    
    $endTime = microtime(true);
    $endMemory = memory_get_usage();
    
    $logData = [
        'operation' => $operationName,
        'execution_time' => round(($endTime - $startTime) * 1000, 2) . 'ms',
        'memory_used' => round(($endMemory - $startMemory) / 1024, 2) . 'KB',
        'success' => $success,
        'error' => $error,
        'timestamp' => date('c')
    ];
    
    error_log(json_encode($logData), 3, $logFile);
    
    return $result;
}

// Usage example
$result = measureAndLog(function() {
    // Simulation of heavy processing
    sleep(1);
    return "Processing completed";
}, "heavy_calculation");
?>

Practical Log Management and Monitoring

<?php
// Level-based log class (error_log() based)
class SimpleLogger {
    private $logFile;
    private $logLevel;
    
    const LEVELS = [
        'DEBUG' => 0,
        'INFO' => 1,
        'WARNING' => 2,
        'ERROR' => 3,
        'CRITICAL' => 4
    ];
    
    public function __construct($logFile = null, $logLevel = 'INFO') {
        $this->logFile = $logFile ?: '/var/log/php/simple_logger.log';
        $this->logLevel = self::LEVELS[$logLevel] ?? 1;
    }
    
    private function log($level, $message, $context = []) {
        if (self::LEVELS[$level] < $this->logLevel) {
            return;  // Insufficient log level
        }
        
        $timestamp = date('Y-m-d H:i:s');
        $pid = getmypid();
        $contextStr = empty($context) ? '' : ' ' . json_encode($context);
        
        $logEntry = sprintf(
            "[%s] [PID:%d] [%s] %s%s",
            $timestamp,
            $pid,
            $level,
            $message,
            $contextStr
        );
        
        error_log($logEntry, 3, $this->logFile);
    }
    
    public function debug($message, $context = []) {
        $this->log('DEBUG', $message, $context);
    }
    
    public function info($message, $context = []) {
        $this->log('INFO', $message, $context);
    }
    
    public function warning($message, $context = []) {
        $this->log('WARNING', $message, $context);
    }
    
    public function error($message, $context = []) {
        $this->log('ERROR', $message, $context);
    }
    
    public function critical($message, $context = []) {
        $this->log('CRITICAL', $message, $context);
        
        // Critical errors also notified via email
        if (defined('ADMIN_EMAIL')) {
            error_log("CRITICAL ERROR: $message", 1, ADMIN_EMAIL);
        }
    }
}

// Usage example
$logger = new SimpleLogger('/var/log/myapp/app.log', 'INFO');

$logger->info("Application started");
$logger->warning("Configuration file not found", ['file' => 'config.ini']);
$logger->error("Database connection failed", ['host' => 'localhost', 'port' => 3306]);

// Log rotation management
class LogRotator {
    public static function rotateIfNeeded($logFile, $maxSize = 10485760) { // 10MB
        if (!file_exists($logFile)) {
            return;
        }
        
        if (filesize($logFile) > $maxSize) {
            $backupFile = $logFile . '.' . date('Ymd_His');
            rename($logFile, $backupFile);
            
            // Compression (if gzip is available)
            if (function_exists('gzencode')) {
                $compressed = gzencode(file_get_contents($backupFile));
                file_put_contents($backupFile . '.gz', $compressed);
                unlink($backupFile);
            }
        }
    }
}

// Regular log rotation execution
LogRotator::rotateIfNeeded('/var/log/myapp/app.log');

// Security-aware logging
function secureLog($message, $logFile = '/var/log/security.log') {
    // Mask sensitive information
    $maskedMessage = preg_replace('/password[=:\s]+\S+/i', 'password=***', $message);
    $maskedMessage = preg_replace('/token[=:\s]+\S+/i', 'token=***', $maskedMessage);
    $maskedMessage = preg_replace('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', '***@***.***', $maskedMessage);
    
    $clientIP = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    
    $secureLogEntry = sprintf(
        "[%s] [IP:%s] [UA:%s] %s",
        date('Y-m-d H:i:s'),
        $clientIP,
        substr($userAgent, 0, 100),  // User-Agent up to 100 characters
        $maskedMessage
    );
    
    error_log($secureLogEntry, 3, $logFile);
}

// Usage example
secureLog("Login attempt: [email protected] password=secret123");
secureLog("API call: token=abc123xyz endpoint=/api/users");

// Real-time monitoring support
// Real-time monitoring in unix environment by cooperating with tail command
// tail -f /var/log/myapp/app.log | grep ERROR
// tail -f /var/log/myapp/app.log | grep "$(date '+%Y-%m-%d')"
?>

Production Environment Optimization and Troubleshooting

<?php
// Configuration optimization for production environment
class ProductionErrorLogger {
    private static $initialized = false;
    
    public static function initialize() {
        if (self::$initialized) return;
        
        // Recommended production settings
        ini_set('display_errors', 0);
        ini_set('display_startup_errors', 0);
        ini_set('log_errors', 1);
        ini_set('log_errors_max_len', 1024);
        ini_set('ignore_repeated_errors', 1);
        ini_set('ignore_repeated_source', 1);
        
        // Log file configuration
        $logDir = '/var/log/php';
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }
        ini_set('error_log', $logDir . '/production_errors.log');
        
        self::$initialized = true;
    }
    
    // Priority-based log output
    public static function logCritical($message, $context = []) {
        $logEntry = self::formatLogEntry('CRITICAL', $message, $context);
        error_log($logEntry, 3, '/var/log/php/critical_errors.log');
        
        // Critical errors immediately notified via email
        if (defined('EMERGENCY_EMAIL')) {
            error_log($logEntry, 1, EMERGENCY_EMAIL);
        }
    }
    
    public static function logBusinessLogic($message, $context = []) {
        $logEntry = self::formatLogEntry('BUSINESS', $message, $context);
        error_log($logEntry, 3, '/var/log/php/business_logic.log');
    }
    
    public static function logPerformance($operation, $duration, $memory = null) {
        $perfData = [
            'operation' => $operation,
            'duration_ms' => round($duration * 1000, 2),
            'memory_mb' => $memory ? round($memory / 1024 / 1024, 2) : null,
            'timestamp' => date('c')
        ];
        
        error_log(json_encode($perfData), 3, '/var/log/php/performance.log');
    }
    
    private static function formatLogEntry($level, $message, $context = []) {
        return sprintf(
            "[%s] [%s] [PID:%d] %s %s",
            date('Y-m-d H:i:s'),
            $level,
            getmypid(),
            $message,
            empty($context) ? '' : '| Context: ' . json_encode($context)
        );
    }
}

// Initialization
ProductionErrorLogger::initialize();

// Comprehensive log collection when errors occur
function collectSystemInfo() {
    return [
        'php_version' => PHP_VERSION,
        'memory_usage' => memory_get_usage(true),
        'memory_peak' => memory_get_peak_usage(true),
        'time' => microtime(true),
        'request_uri' => $_SERVER['REQUEST_URI'] ?? '',
        'http_method' => $_SERVER['REQUEST_METHOD'] ?? '',
        'user_ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ];
}

// Database operation log
function logDatabaseOperation($query, $params = [], $duration = null, $error = null) {
    $logData = [
        'query' => substr($query, 0, 200), // Limit query to 200 characters
        'params_count' => count($params),
        'duration_ms' => $duration ? round($duration * 1000, 2) : null,
        'error' => $error,
        'timestamp' => date('c')
    ];
    
    $logLevel = $error ? 'ERROR' : 'INFO';
    $message = sprintf("[DB_%s] %s", $logLevel, json_encode($logData));
    
    error_log($message, 3, '/var/log/php/database.log');
}

// Log file management tool
class LogFileManager {
    // Log file size monitoring
    public static function checkLogSize($logFile, $maxSizeMB = 50) {
        if (!file_exists($logFile)) return;
        
        $sizeMB = filesize($logFile) / 1024 / 1024;
        if ($sizeMB > $maxSizeMB) {
            error_log(
                "WARNING: Log file size exceeded limit {$logFile}: {$sizeMB}MB",
                3,
                '/var/log/php/system_alerts.log'
            );
        }
    }
    
    // Automatic deletion of old log files
    public static function cleanOldLogs($logDir, $daysToKeep = 30) {
        $files = glob($logDir . '/*.log.*');
        $cutoffTime = time() - ($daysToKeep * 24 * 60 * 60);
        
        foreach ($files as $file) {
            if (filemtime($file) < $cutoffTime) {
                unlink($file);
                error_log("Deleted old log file: $file", 3, '/var/log/php/maintenance.log');
            }
        }
    }
}

// Usage example
try {
    // Execute important processing
    $startTime = microtime(true);
    $startMemory = memory_get_usage();
    
    // Execute business logic
    performCriticalOperation();
    
    $duration = microtime(true) - $startTime;
    $memoryUsed = memory_get_usage() - $startMemory;
    
    ProductionErrorLogger::logPerformance('critical_operation', $duration, $memoryUsed);
    ProductionErrorLogger::logBusinessLogic('Critical processing completed', collectSystemInfo());
    
} catch (Exception $e) {
    ProductionErrorLogger::logCritical(
        'Error occurred in critical processing: ' . $e->getMessage(),
        [
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString()
        ]
    );
}

// Regular maintenance (executed by cron, etc.)
LogFileManager::checkLogSize('/var/log/php/production_errors.log');
LogFileManager::cleanOldLogs('/var/log/php', 30);
?>