You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.4 KiB

  1. <?php
  2. namespace App\Utilities\Logger;
  3. use DateTimeZone;
  4. use InvalidArgumentException;
  5. use Monolog\Logger as Monolog;
  6. use Monolog\Handler\HandlerInterface;
  7. use App\HiLib\Logger\LogServiceRecordProcessor;
  8. class CreateCustomLogger
  9. {
  10. protected $levels = [
  11. 'debug' => Monolog::DEBUG,
  12. 'info' => Monolog::INFO,
  13. 'notice' => Monolog::NOTICE,
  14. 'warning' => Monolog::WARNING,
  15. 'error' => Monolog::ERROR,
  16. 'critical' => Monolog::CRITICAL,
  17. 'alert' => Monolog::ALERT,
  18. 'emergency' => Monolog::EMERGENCY,
  19. ];
  20. public function __invoke(array $config)
  21. {
  22. if (!is_a($config['handler'], HandlerInterface::class, true)) {
  23. throw new InvalidArgumentException(
  24. $config['handler'] . ' must be an instance of ' . HandlerInterface::class
  25. );
  26. }
  27. $with = array_merge(
  28. ['level' => $this->level($config)],
  29. $config['with'] ?? [],
  30. $config['handler_with'] ?? []
  31. );
  32. $handlers = [
  33. $this->prepareHandler(app()->make($config['handler'], $with), $config)
  34. ];
  35. $processors = [
  36. new LogServiceRecordProcessor,
  37. ];
  38. return new Monolog('custom', $handlers, $processors, new DateTimeZone('Asia/Tehran'));
  39. }
  40. protected function getFallbackChannelName()
  41. {
  42. return app()->bound('env') ? app()->environment() : 'production';
  43. }
  44. protected function prepareHandler(HandlerInterface $handler, array $config = [])
  45. {
  46. $isHandlerFormattable = false;
  47. if (Monolog::API === 1) {
  48. $isHandlerFormattable = true;
  49. } elseif (Monolog::API === 2 && $handler instanceof FormattableHandlerInterface) {
  50. $isHandlerFormattable = true;
  51. }
  52. if ($isHandlerFormattable && !isset($config['formatter'])) {
  53. $handler->setFormatter($this->formatter());
  54. } elseif ($isHandlerFormattable && $config['formatter'] !== 'default') {
  55. $handler->setFormatter(app()->make($config['formatter'], $config['formatter_with'] ?? []));
  56. }
  57. return $handler;
  58. }
  59. protected function level(array $config)
  60. {
  61. $level = $config['level'] ?? 'debug';
  62. if (isset($this->levels[$level])) {
  63. return $this->levels[$level];
  64. }
  65. throw new InvalidArgumentException('Invalid log level.');
  66. }
  67. }