萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 強制顯示錯誤並寫入日誌檔案

PHP 運行時強制顯示錯誤並輸出到日誌檔案

在開發或除錯階段,確保所有錯誤(含 Notice、Warning、Fatal)都能被看見並記錄,是快速定位問題的關鍵。以下三行程式碼放在腳本最開頭 (或共用設定檔) 即可啟用完整錯誤報告與日誌記錄。

核心設定程式碼

<?php
// 1. 回報所有等級錯誤 (E_ALL 包含 E_STRICT, E_DEPRECATED 等)
error_reporting(E_ALL);

// 2. 強制在瀏覽器/終端機顯示錯誤訊息
ini_set('display_errors', '1');

// 3. 指定錯誤日誌檔案路徑 (需確保目錄可寫入)
ini_set('error_log', __DIR__ . '/error_log.txt');
?>

參數詳細說明

指令說明建議值
error_reporting(E_ALL)設定要回報的錯誤等級位元遮罩開發環境:E_ALL
正式環境:E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
ini_set('display_errors', '1')是否在輸出中直接顯示錯誤開發:1 (On)
正式:0 (Off) — 避免洩露路徑、SQL 等敏感資訊
ini_set('error_log', 'path')指定錯誤寫入的檔案路徑絕對路徑,如 /var/log/php/error_log 或 __DIR__.'/logs/error.log'

進階:自訂錯誤處理器 (捕捉致命錯誤)

ini_set 無法捕捉 E_ERROR、E_PARSE、E_CORE_ERROR 等導致腳本終止的錯誤。需註冊 set_error_handler()、set_exception_handler()、register_shutdown_function() 組合處理:

<?php
// 開發環境完整錯誤處理組合
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('error_log', __DIR__ . '/error_log.txt');
ini_set('log_errors', '1'); // 確保啟用 log_errors

// 1. 一般錯誤 (Warning, Notice 等)
set_error_handler(function ($severity, $message, $file, $line) {
    $msg = "[ERROR] [$severity] $message in $file:$line\n";
    error_log($msg);
    if (ini_get('display_errors')) {
        echo "
$msg
"; } return true; // 繼續執行內建處理器 }); // 2. 未捕捉例外 set_exception_handler(function ($e) { $msg = "[EXCEPTION] {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}\n{$e->getTraceAsString()}\n"; error_log($msg); if (ini_get('display_errors')) { echo "
$msg
"; } }); // 3. 致命錯誤 / 腳本結束時檢查 register_shutdown_function(function () { $error = error_get_last(); if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) { $msg = "[FATAL] {$error['message']} in {$error['file']}:{$error['line']}\n"; error_log($msg); if (ini_get('display_errors')) { echo "
$msg
"; } } }); ?>

正式環境部署建議

  • display_errors = Off、log_errors = On
  • 日誌檔放在公開目錄外 (/var/log/php/),並設定 logrotate 定期切割。
  • 整合 Monolog、Sentry、Laravel Telescope 等專業日誌/監控工具。
  • 關閉 html_errors 避免日誌混入 HTML 標籤。
copyright © 萬盛學電腦網 all rights reserved