|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Infra\Support; |
| 6 | + |
| 7 | +use RuntimeException; |
| 8 | + |
| 9 | +class Log |
| 10 | +{ |
| 11 | + const LEVEL_INFO = 'INFO'; |
| 12 | + |
| 13 | + const LEVEL_DEBUG = 'DEBUG'; |
| 14 | + |
| 15 | + const LEVEL_WARN = 'WARN'; |
| 16 | + |
| 17 | + const LEVEL_ERROR = 'ERROR'; |
| 18 | + |
| 19 | + private static ?self $instance = null; |
| 20 | + |
| 21 | + private string $filePath; |
| 22 | + |
| 23 | + /** @var resource */ |
| 24 | + private $fileHandle; |
| 25 | + |
| 26 | + private function __construct() |
| 27 | + { |
| 28 | + $logsDirectory = storage_path().'/logs'; |
| 29 | + if (! file_exists($logsDirectory)) { |
| 30 | + // @codeCoverageIgnoreStart |
| 31 | + mkdir($logsDirectory, 0755, true); |
| 32 | + // @codeCoverageIgnoreEnd |
| 33 | + } |
| 34 | + |
| 35 | + $today = date('Ymd'); |
| 36 | + $this->filePath = $logsDirectory."/app-{$today}.log"; |
| 37 | + |
| 38 | + /** @todo delete old log files */ |
| 39 | + $fileHandle = fopen($this->filePath, 'a'); |
| 40 | + |
| 41 | + if (! $fileHandle) { |
| 42 | + // @codeCoverageIgnoreStart |
| 43 | + throw new RuntimeException("Unable to open log file: $this->filePath"); |
| 44 | + // @codeCoverageIgnoreEnd |
| 45 | + } |
| 46 | + |
| 47 | + $this->fileHandle = $fileHandle; |
| 48 | + } |
| 49 | + |
| 50 | + public static function getInstance(): self |
| 51 | + { |
| 52 | + if (self::$instance === null) { |
| 53 | + self::$instance = new self; |
| 54 | + } |
| 55 | + |
| 56 | + return self::$instance; |
| 57 | + } |
| 58 | + |
| 59 | + public function info(string $message): void |
| 60 | + { |
| 61 | + fwrite($this->fileHandle, $this->buildMessage($message, self::LEVEL_INFO)); |
| 62 | + } |
| 63 | + |
| 64 | + public function debug(string $message): void |
| 65 | + { |
| 66 | + fwrite($this->fileHandle, $this->buildMessage($message, self::LEVEL_DEBUG)); |
| 67 | + } |
| 68 | + |
| 69 | + public function warn(string $message): void |
| 70 | + { |
| 71 | + fwrite($this->fileHandle, $this->buildMessage($message, self::LEVEL_WARN)); |
| 72 | + } |
| 73 | + |
| 74 | + public function error(string $message): void |
| 75 | + { |
| 76 | + fwrite($this->fileHandle, $this->buildMessage($message, self::LEVEL_ERROR)); |
| 77 | + } |
| 78 | + |
| 79 | + private function buildMessage(string $message, string $level): string |
| 80 | + { |
| 81 | + /** @todo php timezone is set to UTC, find a way to make it configurable */ |
| 82 | + $timestamp = '['.date('Y-m-d H:i:s', time())."] $level: "; |
| 83 | + |
| 84 | + return $timestamp.$message.PHP_EOL; |
| 85 | + } |
| 86 | + |
| 87 | + public function __destruct() |
| 88 | + { |
| 89 | + // @codeCoverageIgnoreStart |
| 90 | + if ($this->fileHandle !== null) { |
| 91 | + fclose($this->fileHandle); |
| 92 | + } |
| 93 | + // @codeCoverageIgnoreEnd |
| 94 | + } |
| 95 | +} |
0 commit comments