LoggerTest.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\HttpKernel\Tests\Log;
  11. use PHPUnit\Framework\TestCase;
  12. use Psr\Log\LoggerInterface;
  13. use Psr\Log\LogLevel;
  14. use Symfony\Component\HttpKernel\Log\Logger;
  15. /**
  16. * @author Kévin Dunglas <dunglas@gmail.com>
  17. * @author Jordi Boggiano <j.boggiano@seld.be>
  18. */
  19. class LoggerTest extends TestCase
  20. {
  21. /**
  22. * @var LoggerInterface
  23. */
  24. private $logger;
  25. /**
  26. * @var string
  27. */
  28. private $tmpFile;
  29. protected function setUp()
  30. {
  31. $this->tmpFile = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'log';
  32. $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile);
  33. }
  34. protected function tearDown()
  35. {
  36. if (!@unlink($this->tmpFile)) {
  37. file_put_contents($this->tmpFile, '');
  38. }
  39. }
  40. public static function assertLogsMatch(array $expected, array $given)
  41. {
  42. foreach ($given as $k => $line) {
  43. self::assertThat(1 === preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[\+-][0-9]{2}:[0-9]{2} '.preg_quote($expected[$k]).'/', $line), self::isTrue(), "\"$line\" do not match expected pattern \"$expected[$k]\"");
  44. }
  45. }
  46. /**
  47. * Return the log messages in order.
  48. *
  49. * @return string[]
  50. */
  51. public function getLogs()
  52. {
  53. return file($this->tmpFile, FILE_IGNORE_NEW_LINES);
  54. }
  55. public function testImplements()
  56. {
  57. $this->assertInstanceOf(LoggerInterface::class, $this->logger);
  58. }
  59. /**
  60. * @dataProvider provideLevelsAndMessages
  61. */
  62. public function testLogsAtAllLevels($level, $message)
  63. {
  64. $this->logger->{$level}($message, ['user' => 'Bob']);
  65. $this->logger->log($level, $message, ['user' => 'Bob']);
  66. $expected = [
  67. "[$level] message of level $level with context: Bob",
  68. "[$level] message of level $level with context: Bob",
  69. ];
  70. $this->assertLogsMatch($expected, $this->getLogs());
  71. }
  72. public function provideLevelsAndMessages()
  73. {
  74. return [
  75. LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
  76. LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
  77. LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
  78. LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
  79. LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
  80. LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
  81. LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
  82. LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
  83. ];
  84. }
  85. public function testLogLevelDisabled()
  86. {
  87. $this->logger = new Logger(LogLevel::INFO, $this->tmpFile);
  88. $this->logger->debug('test', ['user' => 'Bob']);
  89. $this->logger->log(LogLevel::DEBUG, 'test', ['user' => 'Bob']);
  90. // Will always be true, but asserts than an exception isn't thrown
  91. $this->assertSame([], $this->getLogs());
  92. }
  93. /**
  94. * @expectedException \Psr\Log\InvalidArgumentException
  95. */
  96. public function testThrowsOnInvalidLevel()
  97. {
  98. $this->logger->log('invalid level', 'Foo');
  99. }
  100. /**
  101. * @expectedException \Psr\Log\InvalidArgumentException
  102. */
  103. public function testThrowsOnInvalidMinLevel()
  104. {
  105. new Logger('invalid');
  106. }
  107. /**
  108. * @expectedException \Psr\Log\InvalidArgumentException
  109. */
  110. public function testInvalidOutput()
  111. {
  112. new Logger(LogLevel::DEBUG, '/');
  113. }
  114. public function testContextReplacement()
  115. {
  116. $logger = $this->logger;
  117. $logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
  118. $expected = ['[info] {Message {nothing} Bob Bar a}'];
  119. $this->assertLogsMatch($expected, $this->getLogs());
  120. }
  121. public function testObjectCastToString()
  122. {
  123. if (method_exists($this, 'createPartialMock')) {
  124. $dummy = $this->createPartialMock(DummyTest::class, ['__toString']);
  125. } else {
  126. $dummy = $this->getMock(DummyTest::class, ['__toString']);
  127. }
  128. $dummy->expects($this->atLeastOnce())
  129. ->method('__toString')
  130. ->will($this->returnValue('DUMMY'));
  131. $this->logger->warning($dummy);
  132. $expected = ['[warning] DUMMY'];
  133. $this->assertLogsMatch($expected, $this->getLogs());
  134. }
  135. public function testContextCanContainAnything()
  136. {
  137. $context = [
  138. 'bool' => true,
  139. 'null' => null,
  140. 'string' => 'Foo',
  141. 'int' => 0,
  142. 'float' => 0.5,
  143. 'nested' => ['with object' => new DummyTest()],
  144. 'object' => new \DateTime(),
  145. 'resource' => fopen('php://memory', 'r'),
  146. ];
  147. $this->logger->warning('Crazy context data', $context);
  148. $expected = ['[warning] Crazy context data'];
  149. $this->assertLogsMatch($expected, $this->getLogs());
  150. }
  151. public function testContextExceptionKeyCanBeExceptionOrOtherValues()
  152. {
  153. $logger = $this->logger;
  154. $logger->warning('Random message', ['exception' => 'oops']);
  155. $logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
  156. $expected = [
  157. '[warning] Random message',
  158. '[critical] Uncaught Exception!',
  159. ];
  160. $this->assertLogsMatch($expected, $this->getLogs());
  161. }
  162. public function testFormatter()
  163. {
  164. $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile, function ($level, $message, $context) {
  165. return json_encode(['level' => $level, 'message' => $message, 'context' => $context]).\PHP_EOL;
  166. });
  167. $this->logger->error('An error', ['foo' => 'bar']);
  168. $this->logger->warning('A warning', ['baz' => 'bar']);
  169. $this->assertSame([
  170. '{"level":"error","message":"An error","context":{"foo":"bar"}}',
  171. '{"level":"warning","message":"A warning","context":{"baz":"bar"}}',
  172. ], $this->getLogs());
  173. }
  174. }
  175. class DummyTest
  176. {
  177. public function __toString()
  178. {
  179. }
  180. }