PsrLogCompatTest.php 5.4 KB

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