生產環境需要輕量、線程安全、跨平台的日誌寫入。核心要點:原子追加、換行符跨平台、時間戳格式化、錯誤處理。
<?php
/**
* 寫入日誌(線程安全、跨平台)
* @param string $message 日誌內容
* @param string $file 日誌文件路徑(預設:同目錄 logfile.log)
* @param string $format 時間格式(預設:Y-m-d H:i:s)
* @return bool 成功返回 true
*/
function writeLog(string $message, string $file = 'logfile.log', string $format = 'Y-m-d H:i:s'): bool {
$line = date($format) . ' ' . $message . PHP_EOL;
// FILE_APPEND 追寫 | LOCK_EX 獨佔鎖(防止併發交錯)
$bytes = @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
return $bytes !== false;
}
// 使用示例
writeLog('用戶登入: user_id=123, ip=192.168.1.1');
writeLog('SQL 錯誤: ' . $pdo->errorInfo()[2], 'error.log');
writeLog('API 請求: ' . json_encode($_POST), 'api.log', 'Y-m-d\TH:i:s.uP'); // ISO8601 帶毫秒
\r\n,Linux/Mac \n)。false 而非拋出警告,由調用方決定錯誤處理。file_put_contents 返回寫入字節數,可用於驗證完整性。<?php
class SimpleLogger {
private $basePath;
private $maxSize; // 字節,如 10MB
public function __construct(string $basePath, int $maxSize = 10 * 1024 * 1024) {
$this->basePath = rtrim($basePath, '/');
$this->maxSize = $maxSize;
}
public function log(string $level, string $message, array $context = []): void {
$file = "{$this->basePath}/{$level}.log";
// 簡單輪轉:超過大小重命名備份
if (file_exists($file) && filesize($file) > $this->maxSize) {
$backup = $file . '.' . date('YmdHis');
@rename($file, $backup);
}
$contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
$line = sprintf('[%s] %s%s%s', date('c'), strtoupper($level), $contextStr, PHP_EOL);
@file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}
public function info(string $msg, array $ctx = []) { $this->log('info', $msg, $ctx); }
public function warning(string $msg, array $ctx = []) { $this->log('warning', $msg, $ctx); }
public function error(string $msg, array $ctx = []) { $this->log('error', $msg, $ctx); }
}
// 使用
$logger = new SimpleLogger(__DIR__ . '/logs');
$logger->info('訂單創建', ['order_id' => 1001, 'amount' => 99.9]);
$logger->error('支付失敗', ['order_id' => 1001, 'code' => 'PAY_TIMEOUT']);
?>
| 特性 | 簡易函數 | SimpleLogger | Monolog |
|---|---|---|---|
| 依賴 | 無 | 無 | Composer 包 |
| 日誌級別 | 無 | 支援 | 完整 PSR-3 |
| 輪轉策略 | 無 | 按大小 | 按大小/日期/手動 |
| 處理器 | 文件 | 文件 | 文件、Socket、Slack、DB、Elasticsearch… |
| 格式化器 | 固定 | 簡單 | LineFormatter, JsonFormatter… |
小項目、腳本、快速原型直接用 writeLog() 單函數足夠。中型項目可引入 SimpleLogger 類獲得分級與輪轉。大型項目、微服務、需集中化日誌分析(ELK)請直接使用 Monolog,符合 PSR-3 標準,生態豐富,避免重複造輪子。