LineFormatterTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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\Formatter;
  11. use Monolog\Test\TestCase;
  12. use Monolog\Level;
  13. /**
  14. * @covers Monolog\Formatter\LineFormatter
  15. */
  16. class LineFormatterTest extends TestCase
  17. {
  18. public function testDefFormatWithString()
  19. {
  20. $formatter = new LineFormatter(null, 'Y-m-d');
  21. $message = $formatter->format($this->getRecord(
  22. Level::Warning,
  23. 'foo',
  24. channel: 'log',
  25. ));
  26. $this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
  27. }
  28. public function testDefFormatWithArrayContext()
  29. {
  30. $formatter = new LineFormatter(null, 'Y-m-d');
  31. $message = $formatter->format($this->getRecord(
  32. Level::Error,
  33. 'foo',
  34. channel: 'meh',
  35. context: [
  36. 'foo' => 'bar',
  37. 'baz' => 'qux',
  38. 'bool' => false,
  39. 'null' => null,
  40. ],
  41. ));
  42. $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message);
  43. }
  44. public function testDefFormatExtras()
  45. {
  46. $formatter = new LineFormatter(null, 'Y-m-d');
  47. $message = $formatter->format($this->getRecord(
  48. Level::Error,
  49. 'log',
  50. channel: 'meh',
  51. extra: ['ip' => '127.0.0.1'],
  52. ));
  53. $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message);
  54. }
  55. public function testFormatExtras()
  56. {
  57. $formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
  58. $message = $formatter->format($this->getRecord(
  59. Level::Error,
  60. 'log',
  61. channel: 'meh',
  62. extra: ['ip' => '127.0.0.1', 'file' => 'test'],
  63. ));
  64. $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message);
  65. }
  66. public function testContextAndExtraOptionallyNotShownIfEmpty()
  67. {
  68. $formatter = new LineFormatter(null, 'Y-m-d', false, true);
  69. $message = $formatter->format($this->getRecord(
  70. Level::Error,
  71. 'log',
  72. channel: 'meh',
  73. ));
  74. $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message);
  75. }
  76. public function testContextAndExtraReplacement()
  77. {
  78. $formatter = new LineFormatter('%context.foo% => %extra.foo%');
  79. $message = $formatter->format($this->getRecord(
  80. Level::Error,
  81. 'log',
  82. channel: 'meh',
  83. context: ['foo' => 'bar'],
  84. extra: ['foo' => 'xbar'],
  85. ));
  86. $this->assertEquals('bar => xbar', $message);
  87. }
  88. public function testDefFormatWithObject()
  89. {
  90. $formatter = new LineFormatter(null, 'Y-m-d');
  91. $message = $formatter->format($this->getRecord(
  92. Level::Error,
  93. 'foobar',
  94. channel: 'meh',
  95. context: [],
  96. extra: ['foo' => new TestFoo, 'bar' => new TestBar, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
  97. ));
  98. $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message);
  99. }
  100. public function testDefFormatWithException()
  101. {
  102. $formatter = new LineFormatter(null, 'Y-m-d');
  103. $message = $formatter->format($this->getRecord(
  104. Level::Critical,
  105. 'foobar',
  106. channel: 'core',
  107. context: ['exception' => new \RuntimeException('Foo')],
  108. ));
  109. $path = str_replace('\\/', '/', json_encode(__FILE__));
  110. $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
  111. }
  112. public function testDefFormatWithExceptionAndStacktrace()
  113. {
  114. $formatter = new LineFormatter(null, 'Y-m-d');
  115. $formatter->includeStacktraces();
  116. $message = $formatter->format($this->getRecord(
  117. Level::Critical,
  118. 'foobar',
  119. channel: 'core',
  120. context: ['exception' => new \RuntimeException('Foo')],
  121. ));
  122. $path = str_replace('\\/', '/', json_encode(__FILE__));
  123. $this->assertMatchesRegularExpression('{^\['.date('Y-m-d').'] core\.CRITICAL: foobar \{"exception":"\[object] \(RuntimeException\(code: 0\): Foo at '.preg_quote(substr($path, 1, -1)).':'.(__LINE__ - 5).'\)\n\[stacktrace]\n#0}', $message);
  124. }
  125. public function testInlineLineBreaksRespectsEscapedBackslashes()
  126. {
  127. $formatter = new LineFormatter(null, 'Y-m-d');
  128. $formatter->allowInlineLineBreaks();
  129. self::assertSame('{"test":"foo'."\n".'bar\\\\name-with-n"}', $formatter->stringify(["test" => "foo\nbar\\name-with-n"]));
  130. self::assertSame('["indexed'."\n".'arrays'."\n".'without'."\n".'key","foo'."\n".'bar\\\\name-with-n"]', $formatter->stringify(["indexed\narrays\nwithout\nkey", "foo\nbar\\name-with-n"]));
  131. self::assertSame('[{"first":"multi-dimensional'."\n".'arrays"},{"second":"foo'."\n".'bar\\\\name-with-n"}]', $formatter->stringify([["first" => "multi-dimensional\narrays"], ["second" => "foo\nbar\\name-with-n"]]));
  132. }
  133. public function testDefFormatWithExceptionAndStacktraceParserFull()
  134. {
  135. $formatter = new LineFormatter(null, 'Y-m-d');
  136. $formatter->includeStacktraces(true, function ($line) {
  137. return $line;
  138. });
  139. $message = $formatter->format($this->getRecord(Level::Critical, context: ['exception' => new \RuntimeException('Foo')]));
  140. $trace = explode('[stacktrace]', $message, 2)[1];
  141. $this->assertStringContainsString('TestSuite.php', $trace);
  142. $this->assertStringContainsString('TestRunner.php', $trace);
  143. }
  144. public function testDefFormatWithExceptionAndStacktraceParserCustom()
  145. {
  146. $formatter = new LineFormatter(null, 'Y-m-d');
  147. $formatter->includeStacktraces(true, function ($line) {
  148. if (strpos($line, 'TestSuite.php') === false) {
  149. return $line;
  150. }
  151. });
  152. $message = $formatter->format($this->getRecord(Level::Critical, context: ['exception' => new \RuntimeException('Foo')]));
  153. $trace = explode('[stacktrace]', $message, 2)[1];
  154. $this->assertStringNotContainsString('TestSuite.php', $trace);
  155. $this->assertStringContainsString('TestRunner.php', $trace);
  156. }
  157. public function testDefFormatWithExceptionAndStacktraceParserEmpty()
  158. {
  159. $formatter = new LineFormatter(null, 'Y-m-d');
  160. $formatter->includeStacktraces(true, function ($line) {
  161. return null;
  162. });
  163. $message = $formatter->format($this->getRecord(Level::Critical, context: ['exception' => new \RuntimeException('Foo')]));
  164. $trace = explode('[stacktrace]', $message, 2)[1];
  165. $this->assertStringNotContainsString('#', $trace);
  166. }
  167. public function testDefFormatWithPreviousException()
  168. {
  169. $formatter = new LineFormatter(null, 'Y-m-d');
  170. $previous = new \LogicException('Wut?');
  171. $message = $formatter->format($this->getRecord(
  172. Level::Critical,
  173. 'foobar',
  174. channel: 'core',
  175. context: ['exception' => new \RuntimeException('Foo', 0, $previous)],
  176. ));
  177. $path = str_replace('\\/', '/', json_encode(__FILE__));
  178. $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 5).')\n[previous exception] [object] (LogicException(code: 0): Wut? at '.substr($path, 1, -1).':'.(__LINE__ - 10).')"} []'."\n", $message);
  179. }
  180. public function testDefFormatWithSoapFaultException()
  181. {
  182. if (!class_exists('SoapFault')) {
  183. $this->markTestSkipped('Requires the soap extension');
  184. }
  185. $formatter = new LineFormatter(null, 'Y-m-d');
  186. $message = $formatter->format($this->getRecord(
  187. Level::Critical,
  188. 'foobar',
  189. channel: 'core',
  190. context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')],
  191. ));
  192. $path = str_replace('\\/', '/', json_encode(__FILE__));
  193. $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: world): bar at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
  194. $message = $formatter->format($this->getRecord(
  195. Level::Critical,
  196. 'foobar',
  197. channel: 'core',
  198. context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])],
  199. ));
  200. $path = str_replace('\\/', '/', json_encode(__FILE__));
  201. $this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: {\"bar\":{\"biz\":\"baz\"},\"foo\":\"world\"}): bar at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
  202. }
  203. public function testBatchFormat()
  204. {
  205. $formatter = new LineFormatter(null, 'Y-m-d');
  206. $message = $formatter->formatBatch([
  207. $this->getRecord(
  208. Level::Critical,
  209. 'bar',
  210. channel: 'test',
  211. ),
  212. $this->getRecord(
  213. Level::Warning,
  214. 'foo',
  215. channel: 'log',
  216. ),
  217. ]);
  218. $this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
  219. }
  220. public function testFormatShouldStripInlineLineBreaks()
  221. {
  222. $formatter = new LineFormatter(null, 'Y-m-d');
  223. $message = $formatter->format($this->getRecord(message: "foo\nbar"));
  224. $this->assertMatchesRegularExpression('/foo bar/', $message);
  225. }
  226. public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()
  227. {
  228. $formatter = new LineFormatter(null, 'Y-m-d', true);
  229. $message = $formatter->format($this->getRecord(message: "foo\nbar"));
  230. $this->assertMatchesRegularExpression('/foo\nbar/', $message);
  231. }
  232. /**
  233. * @dataProvider providerMaxLevelNameLength
  234. */
  235. public function testMaxLevelNameLength(?int $maxLength, Level $logLevel, string $expectedLevelName): void
  236. {
  237. $formatter = new LineFormatter(maxLevelNameLength: $maxLength);
  238. $message = $formatter->format($this->getRecord(message: "foo\nbar", level: $logLevel));
  239. $this->assertStringContainsString("test.$expectedLevelName:", $message);
  240. }
  241. public static function providerMaxLevelNameLength(): array
  242. {
  243. return [
  244. 'info_no_max_length' => [
  245. 'max_length' => null,
  246. 'level' => Level::Info,
  247. 'expected_level_name' => 'INFO',
  248. ],
  249. 'error_max_length_3' => [
  250. 'max_length' => 3,
  251. 'level' => Level::Error,
  252. 'expected_level_name' => 'ERR',
  253. ],
  254. 'debug_max_length_2' => [
  255. 'max_length' => 2,
  256. 'level' => Level::Debug,
  257. 'expected_level_name' => 'DE',
  258. ],
  259. ];
  260. }
  261. }
  262. class TestFoo
  263. {
  264. public string $foo = 'fooValue';
  265. }
  266. class TestBar
  267. {
  268. public function __toString()
  269. {
  270. return 'bar';
  271. }
  272. }