|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Hejunjie\Tools\Log\Handlers; |
| 4 | + |
| 5 | +use Hejunjie\Tools\Log\LogFormatterInterface; |
| 6 | +use Hejunjie\Tools\Log\LogHandlerInterface; |
| 7 | +use Hejunjie\Tools\Log\Formatters\DefaultFormatter; |
| 8 | + |
| 9 | +/** |
| 10 | + * 文件日志处理器 |
| 11 | + * |
| 12 | + * @package Hejunjie\Tools\Log\Handlers |
| 13 | + */ |
| 14 | +class FileHandler implements LogHandlerInterface |
| 15 | +{ |
| 16 | + private string $logDir; // 日志存放目录 |
| 17 | + private int $maxFileSize; // 最大文件大小(单位:字节) |
| 18 | + private LogFormatterInterface $formatter; |
| 19 | + |
| 20 | + /** |
| 21 | + * 构造函数 |
| 22 | + * |
| 23 | + * @param string $logDir 日志路径 |
| 24 | + * @param int $maxFileSize 最大文件大小 |
| 25 | + * @param LogFormatterInterface $formatter 格式化器 |
| 26 | + * |
| 27 | + * @return void |
| 28 | + */ |
| 29 | + public function __construct(string $logDir, int $maxFileSize = 5000000, LogFormatterInterface $formatter = new DefaultFormatter()) |
| 30 | + { |
| 31 | + $this->logDir = rtrim($logDir, '/') . '/'; |
| 32 | + $this->maxFileSize = $maxFileSize; |
| 33 | + $this->formatter = $formatter; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * 日志处理 |
| 38 | + * |
| 39 | + * @param string $level 日志级别 |
| 40 | + * @param string $title 日志标题 |
| 41 | + * @param string $message 日志内容 |
| 42 | + * @param array $context 上下文 |
| 43 | + * |
| 44 | + * @return void |
| 45 | + */ |
| 46 | + public function handle(string $level, string $title, string $message, array $context = []): void |
| 47 | + { |
| 48 | + $logFile = $this->getLogFile($title); |
| 49 | + $formattedMessage = $this->formatter->format($level, $message, $context); |
| 50 | + |
| 51 | + // 检查文件大小,进行文件分割 |
| 52 | + if (file_exists($logFile) && filesize($logFile) > $this->maxFileSize) { |
| 53 | + $this->rotateLogFiles($logFile); |
| 54 | + } |
| 55 | + |
| 56 | + file_put_contents($logFile, $formattedMessage . PHP_EOL, FILE_APPEND); |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * 获取日志文件 |
| 61 | + * |
| 62 | + * @param string $title 文件名 |
| 63 | + * |
| 64 | + * @return string |
| 65 | + */ |
| 66 | + private function getLogFile(string $title): string |
| 67 | + { |
| 68 | + if (!is_dir($this->logDir)) { |
| 69 | + mkdir($this->logDir, 0777, true); |
| 70 | + } |
| 71 | + return "{$this->logDir}{$title}.log"; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * 滚动日志文件(log_1.log, log_2.log ...) |
| 76 | + * |
| 77 | + * @param string $logFile 日志文件 |
| 78 | + * |
| 79 | + * @return void |
| 80 | + */ |
| 81 | + private function rotateLogFiles(string $logFile): void |
| 82 | + { |
| 83 | + $index = 1; |
| 84 | + while (file_exists("{$logFile}.{$index}")) { |
| 85 | + $index++; |
| 86 | + } |
| 87 | + rename($logFile, "{$logFile}.{$index}"); |
| 88 | + } |
| 89 | +} |
0 commit comments