LoggerServiceProvider.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Artful\Service;
  4. use Monolog\Formatter\LineFormatter;
  5. use Monolog\Handler\AbstractProcessingHandler;
  6. use Monolog\Handler\RotatingFileHandler;
  7. use Monolog\Handler\StreamHandler;
  8. use Monolog\Logger;
  9. use Yansongda\Artful\Artful;
  10. use Yansongda\Artful\Contract\ConfigInterface;
  11. use Yansongda\Artful\Contract\LoggerInterface;
  12. use Yansongda\Artful\Contract\ServiceProviderInterface;
  13. use Yansongda\Artful\Exception\ContainerException;
  14. use Yansongda\Artful\Exception\ServiceNotFoundException;
  15. class LoggerServiceProvider implements ServiceProviderInterface
  16. {
  17. protected array $config = [
  18. 'enable' => false,
  19. 'file' => null,
  20. 'identify' => 'yansongda.artful',
  21. 'level' => 'DEBUG',
  22. 'type' => 'daily',
  23. 'max_files' => 30,
  24. 'formatter' => "%datetime% > %channel%.%level_name% > %message% %context% %extra%\n\n",
  25. ];
  26. /**
  27. * @throws ContainerException
  28. * @throws ServiceNotFoundException
  29. */
  30. public function register(mixed $data = null): void
  31. {
  32. /* @var ConfigInterface $config */
  33. $config = Artful::get(ConfigInterface::class);
  34. $this->config = array_merge($this->config, $config->get('logger', []));
  35. if (class_exists(Logger::class) && (true === ($this->config['enable'] ?? false))) {
  36. $logger = new Logger($this->config['identify']);
  37. $logger->pushHandler($this->getDefaultHandler()
  38. ->setFormatter($this->getDefaultFormatter()));
  39. Artful::set(LoggerInterface::class, $logger);
  40. }
  41. }
  42. protected function getDefaultFormatter(): LineFormatter
  43. {
  44. return new LineFormatter(
  45. $this->config['formatter'],
  46. null,
  47. false,
  48. true
  49. );
  50. }
  51. protected function getDefaultHandler(): AbstractProcessingHandler
  52. {
  53. $file = $this->config['file'] ?? (sys_get_temp_dir().'/logs/'.$this->config['identify'].'.log');
  54. return match ($this->config['type']) {
  55. 'single' => new StreamHandler($file, $this->config['level']),
  56. default => new RotatingFileHandler($file, $this->config['max_files'], $this->config['level']),
  57. };
  58. }
  59. }