PsrLogCompatTest.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog;
  11. use DateTimeZone;
  12. use Monolog\Handler\TestHandler;
  13. use Monolog\Formatter\LineFormatter;
  14. use Monolog\Processor\PsrLogMessageProcessor;
  15. use PHPUnit\Framework\Attributes\DataProvider;
  16. use PHPUnit\Framework\MockObject\MockObject;
  17. use Psr\Log\InvalidArgumentException;
  18. use Psr\Log\LoggerInterface;
  19. use Psr\Log\LogLevel;
  20. use Stringable;
  21. class PsrLogCompatTest extends \Monolog\Test\MonologTestCase
  22. {
  23. private TestHandler $handler;
  24. public function tearDown(): void
  25. {
  26. parent::tearDown();
  27. unset($this->handler);
  28. }
  29. public function getLogger(): LoggerInterface
  30. {
  31. $logger = new Logger('foo');
  32. $logger->pushHandler($handler = new TestHandler);
  33. $logger->pushProcessor(new PsrLogMessageProcessor);
  34. $handler->setFormatter(new LineFormatter('%level_name% %message%'));
  35. $this->handler = $handler;
  36. return $logger;
  37. }
  38. public function getLogs(): array
  39. {
  40. $convert = function ($record) {
  41. $lower = function ($match) {
  42. return strtolower($match[0]);
  43. };
  44. return preg_replace_callback('{^[A-Z]+}', $lower, $record->formatted);
  45. };
  46. return array_map($convert, $this->handler->getRecords());
  47. }
  48. public function testImplements()
  49. {
  50. $this->assertInstanceOf(LoggerInterface::class, $this->getLogger());
  51. }
  52. #[DataProvider('provideLevelsAndMessages')]
  53. public function testLogsAtAllLevels($level, $message)
  54. {
  55. $logger = $this->getLogger();
  56. $logger->{$level}($message, ['user' => 'Bob']);
  57. $logger->log($level, $message, ['user' => 'Bob']);
  58. $expected = [
  59. "$level message of level $level with context: Bob",
  60. "$level message of level $level with context: Bob",
  61. ];
  62. $this->assertEquals($expected, $this->getLogs());
  63. }
  64. public static function provideLevelsAndMessages()
  65. {
  66. return [
  67. LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
  68. LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
  69. LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
  70. LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
  71. LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
  72. LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
  73. LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
  74. LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
  75. ];
  76. }
  77. public function testThrowsOnInvalidLevel()
  78. {
  79. $logger = $this->getLogger();
  80. $this->expectException(InvalidArgumentException::class);
  81. $logger->log('invalid level', 'Foo');
  82. }
  83. public function testContextReplacement()
  84. {
  85. $logger = $this->getLogger();
  86. $logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
  87. $expected = ['info {Message {nothing} Bob Bar a}'];
  88. $this->assertEquals($expected, $this->getLogs());
  89. }
  90. public function testObjectCastToString()
  91. {
  92. $string = uniqid('DUMMY');
  93. $dummy = $this->createStringable($string);
  94. $dummy->expects($this->once())
  95. ->method('__toString');
  96. $this->getLogger()->warning($dummy);
  97. $expected = ["warning $string"];
  98. $this->assertEquals($expected, $this->getLogs());
  99. }
  100. public function testContextCanContainAnything()
  101. {
  102. $closed = fopen('php://memory', 'r');
  103. fclose($closed);
  104. $context = [
  105. 'bool' => true,
  106. 'null' => null,
  107. 'string' => 'Foo',
  108. 'int' => 0,
  109. 'float' => 0.5,
  110. 'nested' => ['with object' => $this->createStringable()],
  111. 'object' => new \DateTime('now', new DateTimeZone('Europe/London')),
  112. 'resource' => fopen('php://memory', 'r'),
  113. 'closed' => $closed,
  114. ];
  115. $this->getLogger()->warning('Crazy context data', $context);
  116. $expected = ['warning Crazy context data'];
  117. $this->assertEquals($expected, $this->getLogs());
  118. }
  119. public function testContextExceptionKeyCanBeExceptionOrOtherValues()
  120. {
  121. $logger = $this->getLogger();
  122. $logger->warning('Random message', ['exception' => 'oops']);
  123. $logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
  124. $expected = [
  125. 'warning Random message',
  126. 'critical Uncaught Exception!',
  127. ];
  128. $this->assertEquals($expected, $this->getLogs());
  129. }
  130. /**
  131. * Creates a mock of a `Stringable`.
  132. *
  133. * @param string $string The string that must be represented by the stringable.
  134. */
  135. protected function createStringable(string $string = ''): MockObject&Stringable
  136. {
  137. $mock = $this->getMockBuilder(Stringable::class)
  138. ->getMock();
  139. $mock->method('__toString')
  140. ->willReturn($string);
  141. return $mock;
  142. }
  143. }