Logger.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Webservice;
  6. use Magento\Framework\Logger\Monolog;
  7. use Temando\Shipping\Rest\Exception\RestClientErrorException;
  8. use Temando\Shipping\Webservice\Config\WsConfigInterface;
  9. use Temando\Shipping\Webservice\Exception\HttpResponseException;
  10. /**
  11. * Webservice communication logger
  12. *
  13. * @package Temando\Shipping\Webservice
  14. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  15. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  16. * @link http://www.temando.com/
  17. */
  18. class Logger extends Monolog
  19. {
  20. /**
  21. * @var WsConfigInterface
  22. */
  23. private $config;
  24. /**
  25. * Logger constructor.
  26. * @param string $name
  27. * @param WsConfigInterface $config
  28. * @param \Monolog\Handler\HandlerInterface[] $handlers
  29. * @param callable[] $processors
  30. */
  31. public function __construct(
  32. $name,
  33. WsConfigInterface $config,
  34. array $handlers = [],
  35. array $processors = []
  36. ) {
  37. $this->config = $config;
  38. parent::__construct($name, $handlers, $processors);
  39. }
  40. /**
  41. * @param string $message
  42. * @param mixed[] $context
  43. * @return string
  44. */
  45. private function addMessageContext($message, array $context = [])
  46. {
  47. if (isset($context['exception']) && ($context['exception'] instanceof RestClientErrorException)) {
  48. /** @var RestClientErrorException $exception */
  49. $exception = $context['exception'];
  50. $previous = $exception->getPrevious();
  51. if ($previous instanceof HttpResponseException) {
  52. $message = sprintf("%s\n%s", $previous->getResponseHeaders(), $message);
  53. }
  54. }
  55. return $message;
  56. }
  57. /**
  58. * Log message if logging is enabled via module config.
  59. * Disregard module config in error cases.
  60. *
  61. * @param mixed $level
  62. * @param string $message
  63. * @param array $context
  64. * @return bool
  65. */
  66. public function log($level, $message, array $context = [])
  67. {
  68. $monologLevel = parent::toMonologLevel($level);
  69. if ($this->config->isLoggingEnabled() || $monologLevel >= Monolog::ERROR) {
  70. $message = $this->addMessageContext($message, $context);
  71. return parent::log($level, $message, $context);
  72. }
  73. return false;
  74. }
  75. }