2
0

LineFormatterTest.php 12 KB

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