LSlog::get_debug_backtrace_context(): add $with_args, $ignore_last_frames and $prefix arguments

This commit is contained in:
Benjamin Renard 2024-09-26 13:53:45 +02:00
parent d72f45ebb2
commit 3c94ad6bb0
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -310,29 +310,42 @@ class LSlog {
/** /**
* Generate current context backtrace * Generate current context backtrace
* * @param bool $with_args Add args (optional, default: false)
* @param int|null $ignore_last_frames Ignore last frames (optional, default: 1)
* @param string|null $prefix Prefix to append at the beginning of each return lines (optional,
* default: no prefix)
* @return string Current context backtrace * @return string Current context backtrace
**/ **/
public static function get_debug_backtrace_context() { public static function get_debug_backtrace_context($with_args=false, $ignore_last_frames=null, $prefix=null) {
$ignore_last_frames = is_int($ignore_last_frames)?$ignore_last_frames:1;
$prefix = is_string($prefix)?$prefix:"";
$traces = debug_backtrace(); $traces = debug_backtrace();
if (!is_array($traces) || count($traces) < 2) if (!is_array($traces) || count($traces) < ($ignore_last_frames + 1))
return "unknown context"; return $prefix."unknown context";
$msg = array(); $msg = array();
$j=0; $j=0;
for ($i=count($traces)-1; $i >= 1; $i--) { for ($i=count($traces)-1; $i >= (is_int($ignore_last_frames)?$ignore_last_frames:1); $i--) {
$j += 1; $j += 1;
$trace = array("#$j"); $trace = array("#$j");
if (isset($traces[$i]['file'])) if (isset($traces[$i]['file']))
$trace[] = $traces[$i]['file'].(isset($traces[$i]['line'])?":".$traces[$i]['line']:""); $trace[] = $traces[$i]['file'].(isset($traces[$i]['line'])?":".$traces[$i]['line']:"");
$args = (
$with_args && isset($traces[$i]["args"])?
format_callable_args($traces[$i]["args"], $prefix):
""
);
if (isset($traces[$i]['class']) && isset($traces[$i]['function'])) if (isset($traces[$i]['class']) && isset($traces[$i]['function']))
$trace[] = $traces[$i]['class'] . " " . $traces[$i]['type'] . " " . $traces[$i]['function']. "()"; $trace[] = sprintf(
"%s %s %s(%s)",
$traces[$i]['class'], $traces[$i]['type'], $traces[$i]['function'], $args
);
elseif (isset($traces[$i]['function'])) elseif (isset($traces[$i]['function']))
$trace[] = $traces[$i]['function']. "()"; $trace[] = sprintf("%s(%s)", $traces[$i]['function'], $args);
$msg[] = implode(" - ", $trace); $msg[] = $prefix.implode(" - ", $trace);
} }
return implode("\n", $msg); return $prefix.implode("$prefix\n", $msg);
} }
/** /**