PsrLogCompatTest.php 5.5 KB

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