Logger.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. declare(strict_types=1);
  3. namespace Glacier\Core;
  4. /**
  5. * 极简文件日志:storage/logs/app-YYYYMMDD.log,JSON 行格式。
  6. * 生产环境只记日志、不输出详情(错误页由入口按 debug 开关决定)。
  7. */
  8. final class Logger
  9. {
  10. private static ?string $dir = null;
  11. public static function init(string $dir): void
  12. {
  13. self::$dir = rtrim($dir, '/\\');
  14. if (!is_dir(self::$dir)) {
  15. @mkdir(self::$dir, 0775, true);
  16. }
  17. }
  18. public static function info(string $message, array $context = []): void
  19. {
  20. self::write('INFO', $message, $context);
  21. }
  22. public static function warning(string $message, array $context = []): void
  23. {
  24. self::write('WARN', $message, $context);
  25. }
  26. public static function error(string $message, array $context = []): void
  27. {
  28. self::write('ERROR', $message, $context);
  29. }
  30. private static function write(string $level, string $message, array $context): void
  31. {
  32. if (self::$dir === null) {
  33. return;
  34. }
  35. $file = self::$dir . '/app-' . date('Y-m-d') . '.log';
  36. $line = json_encode([
  37. 'ts' => date('Y-m-d H:i:s'),
  38. 'level' => $level,
  39. 'message' => $message,
  40. 'context' => $context,
  41. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  42. @file_put_contents($file, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
  43. }
  44. }