PsrLogCompatTest.php 5.3 KB

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