| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- <?php
- declare(strict_types=1);
- namespace Glacier\Core;
- /**
- * 极简文件日志:storage/logs/app-YYYYMMDD.log,JSON 行格式。
- * 生产环境只记日志、不输出详情(错误页由入口按 debug 开关决定)。
- */
- final class Logger
- {
- private static ?string $dir = null;
- public static function init(string $dir): void
- {
- self::$dir = rtrim($dir, '/\\');
- if (!is_dir(self::$dir)) {
- @mkdir(self::$dir, 0775, true);
- }
- }
- public static function info(string $message, array $context = []): void
- {
- self::write('INFO', $message, $context);
- }
- public static function warning(string $message, array $context = []): void
- {
- self::write('WARN', $message, $context);
- }
- public static function error(string $message, array $context = []): void
- {
- self::write('ERROR', $message, $context);
- }
- private static function write(string $level, string $message, array $context): void
- {
- if (self::$dir === null) {
- return;
- }
- $file = self::$dir . '/app-' . date('Y-m-d') . '.log';
- $line = json_encode([
- 'ts' => date('Y-m-d H:i:s'),
- 'level' => $level,
- 'message' => $message,
- 'context' => $context,
- ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
- @file_put_contents($file, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
- }
- }
|