首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 強制顯示錯誤並記錄到檔案:開發/生產環境雙模式設定

     編輯:PHP 相關知識

快速設定(三行搞定)

<?php
// 1. 回報所有錯誤等級
error_reporting(E_ALL);

// 2. 螢幕顯示錯誤(開發環境用)
ini_set('display_errors', '1');

// 3. 同時寫入錯誤日誌檔案
ini_set('error_log', __DIR__ . '/logs/php_error.log');

環境區分最佳實踐

生產環境絕不應直接顯示錯誤給使用者,會洩露路徑、資料庫結構、敏感變數等資訊。

<?php
// 共用設定
error_reporting(E_ALL);
ini_set('error_log', __DIR__ . '/logs/php_error.log');

// 依環境決定是否顯示
$isProduction = (getenv('APP_ENV') ?? 'development') === 'production';
ini_set('display_errors', $isProduction ? '0' : '1');

// 生產環境可顯示友善錯誤頁面
if ($isProduction) {
    set_error_handler(function ($severity, $message, $file, $line) {
        if (!(error_reporting() & $severity)) return false; // @ 抑制的錯誤不處理
        http_response_code(500);
        require __DIR__ . '/templates/500.php';
        exit;
    });
    
    set_exception_handler(function ($e) {
        http_response_code(500);
        require __DIR__ . '/templates/500.php';
        exit;
    });
}

錯誤等級常數對照

常數涵蓋範圍建議
E_ALL所有錯誤、警告、通知、嚴格標準、Deprecated開發/測試環境推薦
E_ERROR | E_WARNING | E_PARSE僅嚴重錯誤、警告、解析錯誤生產環境記錄用
E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT排除通知、棄用、嚴格標準舊專案過渡期

日誌檔案管理建議

  • 目錄權限:logs/ 需 Web 使用者(www-data/apache)可寫,建議 chmod 775 + 群組寫入。
  • 日誌輪轉:配合 logrotate 每日切割,保留 30 天,避免磁碟爆滿。
  • 格式化:生產環境建議輸出 JSON 格式,便於 ELK/Logstash 收集分析。
<?php
// JSON 格式錯誤日誌(可放入自訂 error handler)
function logErrorJson(int $severity, string $message, string $file, int $line): void
{
    $log = [
        'time'    => date('c'),
        'level'   => errorLevelToString($severity),
        'message' => $message,
        'file'    => $file,
        'line'    => $line,
        'trace'   => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5),
        'request' => [
            'method' => $_SERVER['REQUEST_METHOD'] ?? 'CLI',
            'uri'    => $_SERVER['REQUEST_URI'] ?? '',
            'ip'     => $_SERVER['REMOTE_ADDR'] ?? '',
        ],
    ];
    error_log(json_encode($log, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}

function errorLevelToString(int $level): string
{
    return match ($level) {
        E_ERROR             => 'ERROR',
        E_WARNING           => 'WARNING',
        E_PARSE             => 'PARSE',
        E_NOTICE            => 'NOTICE',
        E_CORE_ERROR        => 'CORE_ERROR',
        E_CORE_WARNING      => 'CORE_WARNING',
        E_COMPILE_ERROR     => 'COMPILE_ERROR',
        E_COMPILE_WARNING   => 'COMPILE_WARNING',
        E_USER_ERROR        => 'USER_ERROR',
        E_USER_WARNING      => 'USER_WARNING',
        E_USER_NOTICE       => 'USER_NOTICE',
        E_STRICT            => 'STRICT',
        E_RECOVERABLE_ERROR => 'RECOVERABLE_ERROR',
        E_DEPRECATED        => 'DEPRECATED',
        E_USER_DEPRECATED   => 'USER_DEPRECATED',
        default             => 'UNKNOWN',
    };
}

總結

  • 開發機:display_errors=1 + error_log 同步寫檔,即時除錯。
  • 生產機:display_errors=0 + 完整 error_log + 自訂錯誤處理器回傳友善頁面。
  • 日誌納入監控系統(ELK/Datadog/Sentry),設定告警門檻,異常即時通知。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved