LoggerTest.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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(): void
  30. {
  31. $this->tmpFile = tempnam(sys_get_temp_dir(), 'log');
  32. $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile);
  33. }
  34. protected function tearDown(): void
  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::assertSame(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), "\"$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(): array
  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 static 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. public function testThrowsOnInvalidLevel()
  94. {
  95. $this->expectException(\Psr\Log\InvalidArgumentException::class);
  96. $this->logger->log('invalid level', 'Foo');
  97. }
  98. public function testThrowsOnInvalidMinLevel()
  99. {
  100. $this->expectException(\Psr\Log\InvalidArgumentException::class);
  101. new Logger('invalid');
  102. }
  103. public function testInvalidOutput()
  104. {
  105. $this->expectException(\Psr\Log\InvalidArgumentException::class);
  106. new Logger(LogLevel::DEBUG, '/');
  107. }
  108. public function testContextReplacement()
  109. {
  110. $logger = $this->logger;
  111. $logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
  112. $expected = ['[info] {Message {nothing} Bob Bar a}'];
  113. $this->assertLogsMatch($expected, $this->getLogs());
  114. }
  115. public function testObjectCastToString()
  116. {
  117. if (method_exists($this, 'createPartialMock')) {
  118. $dummy = $this->createPartialMock(DummyTest::class, ['__toString']);
  119. } else {
  120. $dummy = $this->createPartialMock(DummyTest::class, ['__toString']);
  121. }
  122. $dummy->expects($this->atLeastOnce())
  123. ->method('__toString')
  124. ->willReturn('DUMMY');
  125. $this->logger->warning($dummy);
  126. $expected = ['[warning] DUMMY'];
  127. $this->assertLogsMatch($expected, $this->getLogs());
  128. }
  129. public function testContextCanContainAnything()
  130. {
  131. $context = [
  132. 'bool' => true,
  133. 'null' => null,
  134. 'string' => 'Foo',
  135. 'int' => 0,
  136. 'float' => 0.5,
  137. 'nested' => ['with object' => new DummyTest()],
  138. 'object' => new \DateTime(),
  139. 'resource' => fopen('php://memory', 'r'),
  140. ];
  141. $this->logger->warning('Crazy context data', $context);
  142. $expected = ['[warning] Crazy context data'];
  143. $this->assertLogsMatch($expected, $this->getLogs());
  144. }
  145. public function testContextExceptionKeyCanBeExceptionOrOtherValues()
  146. {
  147. $logger = $this->logger;
  148. $logger->warning('Random message', ['exception' => 'oops']);
  149. $logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
  150. $expected = [
  151. '[warning] Random message',
  152. '[critical] Uncaught Exception!',
  153. ];
  154. $this->assertLogsMatch($expected, $this->getLogs());
  155. }
  156. public function testFormatter()
  157. {
  158. $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile, function ($level, $message, $context) {
  159. return json_encode(['level' => $level, 'message' => $message, 'context' => $context]);
  160. });
  161. $this->logger->error('An error', ['foo' => 'bar']);
  162. $this->logger->warning('A warning', ['baz' => 'bar']);
  163. $this->assertSame([
  164. '{"level":"error","message":"An error","context":{"foo":"bar"}}',
  165. '{"level":"warning","message":"A warning","context":{"baz":"bar"}}',
  166. ], $this->getLogs());
  167. }
  168. public function testLogsWithoutOutput()
  169. {
  170. $oldErrorLog = ini_set('error_log', $this->tmpFile);
  171. $logger = new Logger();
  172. $logger->error('test');
  173. $logger->critical('test');
  174. $expected = [
  175. '[error] test',
  176. '[critical] test',
  177. ];
  178. foreach ($this->getLogs() as $k => $line) {
  179. $this->assertSame(1, preg_match('/\[[\w\/\-: ]+\] '.preg_quote($expected[$k]).'/', $line), "\"$line\" do not match expected pattern \"$expected[$k]\"");
  180. }
  181. ini_set('error_log', $oldErrorLog);
  182. }
  183. }
  184. class DummyTest
  185. {
  186. public function __toString(): string
  187. {
  188. }
  189. }