AccessLogFactory.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. declare(strict_types=1);
  3. namespace Shlinkio\Shlink\Common\Logger\Swoole;
  4. use Interop\Container\ContainerInterface;
  5. use Psr\Log\LoggerInterface;
  6. use Zend\Expressive\Swoole\Log;
  7. use Zend\ServiceManager\Exception\ServiceNotCreatedException;
  8. use Zend\ServiceManager\Exception\ServiceNotFoundException;
  9. use Zend\ServiceManager\Factory\FactoryInterface;
  10. class AccessLogFactory implements FactoryInterface
  11. {
  12. /**
  13. * Create an object
  14. *
  15. * @param ContainerInterface $container
  16. * @param string $requestedName
  17. * @param null|array $options
  18. * @return object
  19. * @throws ServiceNotFoundException if unable to resolve the service.
  20. * @throws ServiceNotCreatedException if an exception is raised when creating a service.
  21. */
  22. public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
  23. {
  24. $config = $container->has('config') ? $container->get('config') : [];
  25. $config = $config['zend-expressive-swoole']['swoole-http-server']['logger'] ?? [];
  26. return new Log\Psr3AccessLogDecorator(
  27. $this->getLogger($container, $config),
  28. $this->getFormatter($container, $config),
  29. $config['use-hostname-lookups'] ?? false
  30. );
  31. }
  32. private function getLogger(ContainerInterface $container, array $config): LoggerInterface
  33. {
  34. $loggerName = $config['logger_name'] ?? LoggerInterface::class;
  35. return $container->has($loggerName) ? $container->get($loggerName) : new Log\StdoutLogger();
  36. }
  37. private function getFormatter(ContainerInterface $container, array $config): Log\AccessLogFormatterInterface
  38. {
  39. if ($container->has(Log\AccessLogFormatterInterface::class)) {
  40. return $container->get(Log\AccessLogFormatterInterface::class);
  41. }
  42. return new Log\AccessLogFormatter($config['format'] ?? Log\AccessLogFormatter::FORMAT_COMMON);
  43. }
  44. }