4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\Tests\Log;
14 use PHPUnit\Framework\TestCase;
15 use Psr\Log\LoggerInterface;
17 use Symfony\Component\HttpKernel\Log\Logger;
20 * @author Kévin Dunglas <dunglas@gmail.com>
21 * @author Jordi Boggiano <j.boggiano@seld.be>
23 class LoggerTest extends TestCase
26 * @var LoggerInterface
35 protected function setUp()
37 $this->tmpFile = sys_get_temp_dir().\DIRECTORY_SEPARATOR.'log';
38 $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile);
41 protected function tearDown()
43 if (!@unlink($this->tmpFile)) {
44 file_put_contents($this->tmpFile, '');
48 public static function assertLogsMatch(array $expected, array $given)
50 foreach ($given as $k => $line) {
51 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]\"");
56 * Return the log messages in order.
60 public function getLogs()
62 return file($this->tmpFile, FILE_IGNORE_NEW_LINES);
65 public function testImplements()
67 $this->assertInstanceOf(LoggerInterface::class, $this->logger);
71 * @dataProvider provideLevelsAndMessages
73 public function testLogsAtAllLevels($level, $message)
75 $this->logger->{$level}($message, array('user' => 'Bob'));
76 $this->logger->log($level, $message, array('user' => 'Bob'));
79 "[$level] message of level $level with context: Bob",
80 "[$level] message of level $level with context: Bob",
82 $this->assertLogsMatch($expected, $this->getLogs());
85 public function provideLevelsAndMessages()
88 LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
89 LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
90 LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
91 LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
92 LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
93 LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
94 LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
95 LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
99 public function testLogLevelDisabled()
101 $this->logger = new Logger(LogLevel::INFO, $this->tmpFile);
103 $this->logger->debug('test', array('user' => 'Bob'));
104 $this->logger->log(LogLevel::DEBUG, 'test', array('user' => 'Bob'));
106 // Will always be true, but asserts than an exception isn't thrown
107 $this->assertSame(array(), $this->getLogs());
111 * @expectedException \Psr\Log\InvalidArgumentException
113 public function testThrowsOnInvalidLevel()
115 $this->logger->log('invalid level', 'Foo');
119 * @expectedException \Psr\Log\InvalidArgumentException
121 public function testThrowsOnInvalidMinLevel()
123 new Logger('invalid');
127 * @expectedException \Psr\Log\InvalidArgumentException
129 public function testInvalidOutput()
131 new Logger(LogLevel::DEBUG, '/');
134 public function testContextReplacement()
136 $logger = $this->logger;
137 $logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
139 $expected = array('[info] {Message {nothing} Bob Bar a}');
140 $this->assertLogsMatch($expected, $this->getLogs());
143 public function testObjectCastToString()
145 if (method_exists($this, 'createPartialMock')) {
146 $dummy = $this->createPartialMock(DummyTest::class, array('__toString'));
148 $dummy = $this->getMock(DummyTest::class, array('__toString'));
150 $dummy->expects($this->atLeastOnce())
151 ->method('__toString')
152 ->will($this->returnValue('DUMMY'));
154 $this->logger->warning($dummy);
156 $expected = array('[warning] DUMMY');
157 $this->assertLogsMatch($expected, $this->getLogs());
160 public function testContextCanContainAnything()
168 'nested' => array('with object' => new DummyTest()),
169 'object' => new \DateTime(),
170 'resource' => fopen('php://memory', 'r'),
173 $this->logger->warning('Crazy context data', $context);
175 $expected = array('[warning] Crazy context data');
176 $this->assertLogsMatch($expected, $this->getLogs());
179 public function testContextExceptionKeyCanBeExceptionOrOtherValues()
181 $logger = $this->logger;
182 $logger->warning('Random message', array('exception' => 'oops'));
183 $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
186 '[warning] Random message',
187 '[critical] Uncaught Exception!',
189 $this->assertLogsMatch($expected, $this->getLogs());
192 public function testFormatter()
194 $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile, function ($level, $message, $context) {
195 return json_encode(array('level' => $level, 'message' => $message, 'context' => $context)).\PHP_EOL;
198 $this->logger->error('An error', array('foo' => 'bar'));
199 $this->logger->warning('A warning', array('baz' => 'bar'));
200 $this->assertSame(array(
201 '{"level":"error","message":"An error","context":{"foo":"bar"}}',
202 '{"level":"warning","message":"A warning","context":{"baz":"bar"}}',
203 ), $this->getLogs());
209 public function __toString()