Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove base path on LineFormatter #1873

Merged
merged 4 commits into from
Apr 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading