PsrLogCompatTest.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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\TestCase;
  16. use Psr\Log\InvalidArgumentException;
  17. use Psr\Log\LoggerInterface;
  18. use Psr\Log\LogLevel;
  19. use Psr\Log\Test\LoggerInterfaceTest;
  20. class PsrLogCompatTest extends TestCase
  21. {
  22. private $handler;
  23. public function tearDown(): void
  24. {
  25. parent::tearDown();
  26. unset($this->handler);
  27. }
  28. public function getLogger(): LoggerInterface
  29. {
  30. $logger = new Logger('foo');
  31. $logger->pushHandler($handler = new TestHandler);
  32. $logger->pushProcessor(new PsrLogMessageProcessor);
  33. $handler->setFormatter(new LineFormatter('%level_name% %message%'));
  34. $this->handler = $handler;
  35. return $logger;
  36. }
  37. public function getLogs(): array
  38. {
  39. $convert = function ($record) {
  40. $lower = function ($match) {
  41. return strtolower($match[0]);
  42. };
  43. return preg_replace_callback('{^[A-Z]+}', $lower, $record['formatted']);
  44. };
  45. return array_map($convert, $this->handler->getRecords());
  46. }
  47. public function testImplements()
  48. {
  49. $this->assertInstanceOf(LoggerInterface::class, $this->getLogger());
  50. }
  51. /**
  52. * @dataProvider provideLevelsAndMessages
  53. */
  54. public function testLogsAtAllLevels($level, $message)
  55. {
  56. $logger = $this->getLogger();
  57. $logger->{$level}($message, array('user' => 'Bob'));
  58. $logger->log($level, $message, array('user' => 'Bob'));
  59. $expected = array(
  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 function provideLevelsAndMessages()
  66. {
  67. return array(
  68. LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
  69. LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
  70. LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
  71. LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
  72. LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
  73. LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
  74. LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
  75. LogLevel::DEBUG => array(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}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
  88. $expected = array('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 = array("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 = array(
  106. 'bool' => true,
  107. 'null' => null,
  108. 'string' => 'Foo',
  109. 'int' => 0,
  110. 'float' => 0.5,
  111. 'nested' => array('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 = array('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', array('exception' => 'oops'));
  124. $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
  125. $expected = array(
  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. * @return \PHPUnit_Framework_MockObject_MockObject A mock of an object that has a `__toString()` method.
  136. */
  137. protected function createStringable($string = '')
  138. {
  139. $mock = $this->getMockBuilder('Stringable')
  140. ->setMethods(array('__toString'))
  141. ->getMock();
  142. $mock->method('__toString')
  143. ->will($this->returnValue($string));
  144. return $mock;
  145. }
  146. }