Base.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Logger\Handler;
  7. use Magento\Framework\Filesystem\DriverInterface;
  8. use Monolog\Formatter\LineFormatter;
  9. use Monolog\Handler\StreamHandler;
  10. use Monolog\Logger;
  11. /**
  12. * Base stream handler
  13. */
  14. class Base extends StreamHandler
  15. {
  16. /**
  17. * @var string
  18. */
  19. protected $fileName;
  20. /**
  21. * @var int
  22. */
  23. protected $loggerType = Logger::DEBUG;
  24. /**
  25. * @var DriverInterface
  26. */
  27. protected $filesystem;
  28. /**
  29. * @param DriverInterface $filesystem
  30. * @param string $filePath
  31. * @param string $fileName
  32. * @throws \Exception
  33. */
  34. public function __construct(
  35. DriverInterface $filesystem,
  36. $filePath = null,
  37. $fileName = null
  38. ) {
  39. $this->filesystem = $filesystem;
  40. if (!empty($fileName)) {
  41. $this->fileName = $this->sanitizeFileName($fileName);
  42. }
  43. parent::__construct(
  44. $filePath ? $filePath . $this->fileName : BP . DIRECTORY_SEPARATOR . $this->fileName,
  45. $this->loggerType
  46. );
  47. $this->setFormatter(new LineFormatter(null, null, true));
  48. }
  49. /**
  50. * Remove dots from file name
  51. *
  52. * @param string $fileName
  53. * @return string
  54. * @throws \InvalidArgumentException
  55. */
  56. private function sanitizeFileName($fileName)
  57. {
  58. if (!is_string($fileName)) {
  59. throw new \InvalidArgumentException('Filename expected to be a string');
  60. }
  61. $parts = explode('/', $fileName);
  62. $parts = array_filter($parts, function ($value) {
  63. return !in_array($value, ['', '.', '..']);
  64. });
  65. return implode('/', $parts);
  66. }
  67. /**
  68. * @inheritDoc
  69. */
  70. public function write(array $record)
  71. {
  72. $logDir = $this->filesystem->getParentDirectory($this->url);
  73. if (!$this->filesystem->isDirectory($logDir)) {
  74. $this->filesystem->createDirectory($logDir);
  75. }
  76. parent::write($record);
  77. }
  78. }