2
0

LineFormatterTest.php 13 KB

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