1 <?php declare(strict_types=1);
4 * This file is part of the Monolog package.
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Monolog\Formatter;
17 * Formats incoming records into a one-line string
19 * This is especially useful for logging to files
21 * @author Jordi Boggiano <j.boggiano@seld.be>
22 * @author Christophe Coevoet <stof@notk.org>
24 class LineFormatter extends NormalizerFormatter
26 public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";
31 protected $allowInlineLineBreaks;
33 protected $ignoreEmptyContextAndExtra;
35 protected $includeStacktraces;
37 protected $stacktracesParser;
40 * @param string|null $format The format of the message
41 * @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
42 * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
43 * @param bool $ignoreEmptyContextAndExtra
45 public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false)
47 $this->format = $format === null ? static::SIMPLE_FORMAT : $format;
48 $this->allowInlineLineBreaks = $allowInlineLineBreaks;
49 $this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
50 $this->includeStacktraces($includeStacktraces);
51 parent::__construct($dateFormat);
54 public function includeStacktraces(bool $include = true, ?callable $parser = null): self
56 $this->includeStacktraces = $include;
57 if ($this->includeStacktraces) {
58 $this->allowInlineLineBreaks = true;
59 $this->stacktracesParser = $parser;
65 public function allowInlineLineBreaks(bool $allow = true): self
67 $this->allowInlineLineBreaks = $allow;
72 public function ignoreEmptyContextAndExtra(bool $ignore = true): self
74 $this->ignoreEmptyContextAndExtra = $ignore;
82 public function format(array $record): string
84 $vars = parent::format($record);
86 $output = $this->format;
88 foreach ($vars['extra'] as $var => $val) {
89 if (false !== strpos($output, '%extra.'.$var.'%')) {
90 $output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output);
91 unset($vars['extra'][$var]);
95 foreach ($vars['context'] as $var => $val) {
96 if (false !== strpos($output, '%context.'.$var.'%')) {
97 $output = str_replace('%context.'.$var.'%', $this->stringify($val), $output);
98 unset($vars['context'][$var]);
102 if ($this->ignoreEmptyContextAndExtra) {
103 if (empty($vars['context'])) {
104 unset($vars['context']);
105 $output = str_replace('%context%', '', $output);
108 if (empty($vars['extra'])) {
109 unset($vars['extra']);
110 $output = str_replace('%extra%', '', $output);
114 foreach ($vars as $var => $val) {
115 if (false !== strpos($output, '%'.$var.'%')) {
116 $output = str_replace('%'.$var.'%', $this->stringify($val), $output);
120 // remove leftover %extra.xxx% and %context.xxx% if any
121 if (false !== strpos($output, '%')) {
122 $output = preg_replace('/%(?:extra|context)\..+?%/', '', $output);
123 if (null === $output) {
124 $pcreErrorCode = preg_last_error();
125 throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode));
132 public function formatBatch(array $records): string
135 foreach ($records as $record) {
136 $message .= $this->format($record);
143 * @param mixed $value
145 public function stringify($value): string
147 return $this->replaceNewlines($this->convertToString($value));
150 protected function normalizeException(\Throwable $e, int $depth = 0): string
152 $str = $this->formatException($e);
154 if ($previous = $e->getPrevious()) {
157 if ($depth > $this->maxNormalizeDepth) {
158 $str .= "\n[previous exception] Over " . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
162 $str .= "\n[previous exception] " . $this->formatException($previous);
163 } while ($previous = $previous->getPrevious());
172 protected function convertToString($data): string
174 if (null === $data || is_bool($data)) {
175 return var_export($data, true);
178 if (is_scalar($data)) {
179 return (string) $data;
182 return $this->toJson($data, true);
185 protected function replaceNewlines(string $str): string
187 if ($this->allowInlineLineBreaks) {
188 if (0 === strpos($str, '{')) {
189 $str = preg_replace('/(?<!\\\\)\\\\[rn]/', "\n", $str);
191 $pcreErrorCode = preg_last_error();
192 throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . Utils::pcreLastErrorMessage($pcreErrorCode));
199 return str_replace(["\r\n", "\r", "\n"], ' ', $str);
202 private function formatException(\Throwable $e): string
204 $str = '[object] (' . Utils::getClass($e) . '(code: ' . $e->getCode();
205 if ($e instanceof \SoapFault) {
206 if (isset($e->faultcode)) {
207 $str .= ' faultcode: ' . $e->faultcode;
210 if (isset($e->faultactor)) {
211 $str .= ' faultactor: ' . $e->faultactor;
214 if (isset($e->detail)) {
215 if (is_string($e->detail)) {
216 $str .= ' detail: ' . $e->detail;
217 } elseif (is_object($e->detail) || is_array($e->detail)) {
218 $str .= ' detail: ' . $this->toJson($e->detail, true);
222 $str .= '): ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine() . ')';
224 if ($this->includeStacktraces) {
225 $str .= $this->stacktracesParser($e);
231 private function stacktracesParser(\Throwable $e): string
233 $trace = $e->getTraceAsString();
235 if ($this->stacktracesParser) {
236 $trace = $this->stacktracesParserCustom($trace);
239 return "\n[stacktrace]\n" . $trace . "\n";
242 private function stacktracesParserCustom(string $trace): string
244 return implode("\n", array_filter(array_map($this->stacktracesParser, explode("\n", $trace))));