Skip to content

Commit

Permalink
Remove base path on LineFormatter (#1873)
Browse files Browse the repository at this point in the history
  • Loading branch information
cesarreyes3 committed Apr 12, 2024
1 parent c48c642 commit 24e0e45
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/Monolog/Formatter/LineFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
*/
Expand Down Expand Up @@ -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);
Expand All @@ -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);
}
Expand Down

0 comments on commit 24e0e45

Please sign in to comment.