PsrLogCompatTest.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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\MockObject\MockObject;
  16. use PHPUnit\Framework\TestCase;
  17. use Psr\Log\InvalidArgumentException;
  18. use Psr\Log\LoggerInterface;
  19. use Psr\Log\LogLevel;
  20. use Stringable;
  21. class PsrLogCompatTest extends TestCase
  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. /**
  53. * @dataProvider provideLevelsAndMessages
  54. */
  55. public function testLogsAtAllLevels($level, $message)
  56. {
  57. $logger = $this->getLogger();
  58. $logger->{$level}($message, ['user' => 'Bob']);
  59. $logger->log($level, $message, ['user' => 'Bob']);
  60. $expected = [
  61. "$level message of level $level with context: Bob",
  62. "$level message of level $level with context: Bob",
  63. ];
  64. $this->assertEquals($expected, $this->getLogs());
  65. }
  66. public static function provideLevelsAndMessages()
  67. {
  68. return [
  69. LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
  70. LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
  71. LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
  72. LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
  73. LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
  74. LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
  75. LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
  76. LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
  77. ];
  78. }
  79. public function testThrowsOnInvalidLevel()
  80. {
  81. $logger = $this->getLogger();
  82. $this->expectException(InvalidArgumentException::class);
  83. $logger->log('invalid level', 'Foo');
  84. }
  85. public function testContextReplacement()
  86. {
  87. $logger = $this->getLogger();
  88. $logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
  89. $expected = ['info {Message {nothing} Bob Bar a}'];
  90. $this->assertEquals($expected, $this->getLogs());
  91. }
  92. public function testObjectCastToString()
  93. {
  94. $string = uniqid('DUMMY');
  95. $dummy = $this->createStringable($string);
  96. $dummy->expects($this->once())
  97. ->method('__toString');
  98. $this->getLogger()->warning($dummy);
  99. $expected = ["warning $string"];
  100. $this->assertEquals($expected, $this->getLogs());
  101. }
  102. public function testContextCanContainAnything()
  103. {
  104. $closed = fopen('php://memory', 'r');
  105. fclose($closed);
  106. $context = [
  107. 'bool' => true,
  108. 'null' => null,
  109. 'string' => 'Foo',
  110. 'int' => 0,
  111. 'float' => 0.5,
  112. 'nested' => ['with object' => $this->createStringable()],
  113. 'object' => new \DateTime('now', new DateTimeZone('Europe/London')),
  114. 'resource' => fopen('php://memory', 'r'),
  115. 'closed' => $closed,
  116. ];
  117. $this->getLogger()->warning('Crazy context data', $context);
  118. $expected = ['warning Crazy context data'];
  119. $this->assertEquals($expected, $this->getLogs());
  120. }
  121. public function testContextExceptionKeyCanBeExceptionOrOtherValues()
  122. {
  123. $logger = $this->getLogger();
  124. $logger->warning('Random message', ['exception' => 'oops']);
  125. $logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
  126. $expected = [
  127. 'warning Random message',
  128. 'critical Uncaught Exception!',
  129. ];
  130. $this->assertEquals($expected, $this->getLogs());
  131. }
  132. /**
  133. * Creates a mock of a `Stringable`.
  134. *
  135. * @param string $string The string that must be represented by the stringable.
  136. */
  137. protected function createStringable(string $string = ''): MockObject&Stringable
  138. {
  139. $mock = $this->getMockBuilder(Stringable::class)
  140. ->getMock();
  141. $mock->method('__toString')
  142. ->will($this->returnValue($string));
  143. return $mock;
  144. }
  145. }