diff --git a/src/Monolog/Formatter/LineFormatter.php b/src/Monolog/Formatter/LineFormatter.php index 025572a5c..7d35960cc 100644 --- a/src/Monolog/Formatter/LineFormatter.php +++ b/src/Monolog/Formatter/LineFormatter.php @@ -34,6 +34,7 @@ class LineFormatter extends NormalizerFormatter protected ?int $maxLevelNameLength = null; protected string $indentStacktraces = ''; protected Closure|null $stacktracesParser = null; + protected string $basePath = ''; /** * @param string|null $format The format of the message @@ -51,6 +52,21 @@ public function __construct(?string $format = null, ?string $dateFormat = null, parent::__construct($dateFormat); } + /** + * Setting a base path will hide the base path from exception and stack trace file names to shorten them + * @return $this + */ + public function setBasePath(string $path = ''): self + { + if ($path !== '') { + $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; + } + + $this->basePath = $path; + + return $this; + } + /** * @return $this */ @@ -258,7 +274,13 @@ private function formatException(\Throwable $e): string } } } - $str .= '): ' . $e->getMessage() . ' at ' . $e->getFile() . ':' . $e->getLine() . ')'; + + $file = $e->getFile(); + if ($this->basePath !== '') { + $file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file); + } + + $str .= '): ' . $e->getMessage() . ' at ' . $file . ':' . $e->getLine() . ')'; if ($this->includeStacktraces) { $str .= $this->stacktracesParser($e); @@ -271,6 +293,10 @@ private function stacktracesParser(\Throwable $e): string { $trace = $e->getTraceAsString(); + if ($this->basePath !== '') { + $trace = preg_replace('{^(#\d+ )' . preg_quote($this->basePath) . '}m', '$1', $trace) ?? $trace; + } + if ($this->stacktracesParser !== null) { $trace = $this->stacktracesParserCustom($trace); }