LineFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. $this->assertSame(PHP_EOL . PHP_EOL . '"} []' . PHP_EOL, $trace);
  169. }
  170. public function testDefFormatWithPreviousException()
  171. {
  172. $formatter = new LineFormatter(null, 'Y-m-d');
  173. $previous = new \LogicException('Wut?');
  174. $message = $formatter->format($this->getRecord(
  175. Level::Critical,
  176. 'foobar',
  177. channel: 'core',
  178. context: ['exception' => new \RuntimeException('Foo', 0, $previous)],
  179. ));
  180. $path = str_replace('\\/', '/', json_encode(__FILE__));
  181. $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);
  182. }
  183. public function testDefFormatWithSoapFaultException()
  184. {
  185. if (!class_exists('SoapFault')) {
  186. $this->markTestSkipped('Requires the soap extension');
  187. }
  188. $formatter = new LineFormatter(null, 'Y-m-d');
  189. $message = $formatter->format($this->getRecord(
  190. Level::Critical,
  191. 'foobar',
  192. channel: 'core',
  193. context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')],
  194. ));
  195. $path = str_replace('\\/', '/', json_encode(__FILE__));
  196. $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);
  197. $message = $formatter->format($this->getRecord(
  198. Level::Critical,
  199. 'foobar',
  200. channel: 'core',
  201. context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])],
  202. ));
  203. $path = str_replace('\\/', '/', json_encode(__FILE__));
  204. $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);
  205. }
  206. public function testBatchFormat()
  207. {
  208. $formatter = new LineFormatter(null, 'Y-m-d');
  209. $message = $formatter->formatBatch([
  210. $this->getRecord(
  211. Level::Critical,
  212. 'bar',
  213. channel: 'test',
  214. ),
  215. $this->getRecord(
  216. Level::Warning,
  217. 'foo',
  218. channel: 'log',
  219. ),
  220. ]);
  221. $this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
  222. }
  223. public function testFormatShouldStripInlineLineBreaks()
  224. {
  225. $formatter = new LineFormatter(null, 'Y-m-d');
  226. $message = $formatter->format($this->getRecord(message: "foo\nbar"));
  227. $this->assertMatchesRegularExpression('/foo bar/', $message);
  228. }
  229. public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()
  230. {
  231. $formatter = new LineFormatter(null, 'Y-m-d', true);
  232. $message = $formatter->format($this->getRecord(message: "foo\nbar"));
  233. $this->assertMatchesRegularExpression('/foo\nbar/', $message);
  234. }
  235. public function testIndentStackTraces(): void
  236. {
  237. $formatter = new LineFormatter();
  238. $formatter->includeStacktraces();
  239. //$formatter->allowInlineLineBreaks();
  240. $formatter->indentStackTraces(' ');
  241. $message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));
  242. $this->assertStringContainsString(' [stacktrace]', $message);
  243. $this->assertStringContainsString(' #0', $message);
  244. $this->assertStringContainsString(' #1', $message);
  245. }
  246. public function testBasePath(): void
  247. {
  248. $formatter = new LineFormatter();
  249. $formatter->includeStacktraces();
  250. $formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
  251. $formatter->indentStackTraces(' ');
  252. $message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));
  253. $this->assertStringContainsString(' [stacktrace]', $message);
  254. $this->assertStringContainsString(' #0 vendor/phpunit/phpunit/src/Framework/TestCase.php', $message);
  255. $this->assertStringContainsString(' #1 vendor/phpunit/phpunit/', $message);
  256. }
  257. #[DataProvider('providerMaxLevelNameLength')]
  258. public function testMaxLevelNameLength(?int $maxLength, Level $logLevel, string $expectedLevelName): void
  259. {
  260. $formatter = new LineFormatter();
  261. $formatter->setMaxLevelNameLength($maxLength);
  262. $message = $formatter->format($this->getRecord(message: "foo\nbar", level: $logLevel));
  263. $this->assertStringContainsString("test.$expectedLevelName:", $message);
  264. }
  265. public static function providerMaxLevelNameLength(): array
  266. {
  267. return [
  268. 'info_no_max_length' => [
  269. 'maxLength' => null,
  270. 'logLevel' => Level::Info,
  271. 'expectedLevelName' => 'INFO',
  272. ],
  273. 'error_max_length_3' => [
  274. 'maxLength' => 3,
  275. 'logLevel' => Level::Error,
  276. 'expectedLevelName' => 'ERR',
  277. ],
  278. 'debug_max_length_2' => [
  279. 'maxLength' => 2,
  280. 'logLevel' => Level::Debug,
  281. 'expectedLevelName' => 'DE',
  282. ],
  283. ];
  284. }
  285. }
  286. class TestFoo
  287. {
  288. public string $foo = 'fooValue';
  289. }
  290. class TestBar
  291. {
  292. public function __toString()
  293. {
  294. return 'bar';
  295. }
  296. }