Compare commits

..

4 commits

Author SHA1 Message Date
Benjamin Renard
000222ae89
LSurl::public_url: fix handling public root URL with a trailing slash 2024-09-26 15:25:25 +02:00
Benjamin Renard
b5b540de65
LSlog: add log_errors_context & log_errors_context_with_args paramters 2024-09-26 15:25:24 +02:00
Benjamin Renard
4c7f6847fd
LSlog::get_debug_backtrace_context(): add & arguments 2024-09-26 15:25:24 +02:00
Benjamin Renard
9f2cbeca6f
Improve format_callable() 2024-09-26 15:25:23 +02:00
4 changed files with 23 additions and 108 deletions

View file

@ -8,7 +8,6 @@ $GLOBALS['LSlog'] = array(
'level' => '[niveau]', 'level' => '[niveau]',
'log_errors_context' => [booléen], 'log_errors_context' => [booléen],
'log_errors_context_with_args' => [booléen], 'log_errors_context_with_args' => [booléen],
'log_errors_context_args_max_length' => [entier],
'handlers' => array( 'handlers' => array(
'[handler 1]', '[handler 1]',
array ( array (
@ -67,12 +66,6 @@ $GLOBALS['LSlog'] = array(
inclus lors de la journalisation du contexte des erreurs. inclus lors de la journalisation du contexte des erreurs.
__Note :__ ce paramètre n'as aucun effet si le paramètre `log_errors_context` n'est pas activé. __Note :__ ce paramètre n'as aucun effet si le paramètre `log_errors_context` n'est pas activé.
- `log_errors_context_args_max_length`
Ce paramètre permet de définir à partir de quelle longueur les arguments des méthodes/fonctions
appelées et journalisés seront tronqués (par défaut : `1000`). __Note :__ pour désactiver le
troncage, mettre ce paramètre à zéro.
- `handlers` - `handlers`
Tableau permettant de configurer les *handlers* de la journalisation. Chaque *handler* gère les Tableau permettant de configurer les *handlers* de la journalisation. Chaque *handler* gère les

View file

@ -211,14 +211,11 @@ $GLOBALS['LSlog'] = array (
// Global logs level (TRACE, DEBUG, INFO, WARNING, ERROR, FATAL) // Global logs level (TRACE, DEBUG, INFO, WARNING, ERROR, FATAL)
'level' => 'INFO', 'level' => 'INFO',
// Log errors's context (=backtrace, default: false) // Log errors's context (=backtrace)
'log_errors_context' => true, 'log_errors_context' => true,
// Log errors's context with arguments of called method/functions (default: false) // Log errors's context with arguments of called method/functions
// 'log_errors_context_with_args' => false, 'log_errors_context_with_args' => false,
// Truncate logged arguments in errors's context (default: 1000)
// 'log_errors_context_args_max_length' => 1000,
/** /**
* Logs handlers are components that logged message emitted by the application. * Logs handlers are components that logged message emitted by the application.

View file

@ -45,12 +45,6 @@ class LSlog {
*/ */
private static $log_errors_context_with_args = false; private static $log_errors_context_with_args = false;
/**
* Log errors context with arguments
* @var int
*/
private static $log_errors_context_args_max_length = 1000;
/** /**
* Configured handlers * Configured handlers
* @see self::start() * @see self::start()
@ -111,7 +105,6 @@ class LSlog {
self :: $enabled = self :: getConfig('enable', false, 'bool'); self :: $enabled = self :: getConfig('enable', false, 'bool');
self :: $log_errors_context = self :: getConfig('log_errors_context', false, 'bool'); self :: $log_errors_context = self :: getConfig('log_errors_context', false, 'bool');
self :: $log_errors_context_with_args = self :: getConfig('log_errors_context_with_args', false, 'bool'); self :: $log_errors_context_with_args = self :: getConfig('log_errors_context_with_args', false, 'bool');
self :: $log_errors_context_args_max_length = self :: getConfig('log_errors_context_args_max_length', 1000, 'int');
self :: setLevel(); self :: setLevel();
// Load default handlers class // Load default handlers class
@ -253,11 +246,10 @@ class LSlog {
* @param string $level The message level * @param string $level The message level
* @param string $message The message * @param string $message The message
* @param string|null $logger The logger name (optional, default: null) * @param string|null $logger The logger name (optional, default: null)
* @param bool $do_not_include_context Set to true to disable context inclusion (optional, default: false)
* *
* @return void * @return void
**/ **/
public static function logging($level, $message, $logger=null, $do_not_include_context=false) { public static function logging($level, $message, $logger=null) {
// Check LSlog is enabled // Check LSlog is enabled
if (!self :: $enabled) if (!self :: $enabled)
return; return;
@ -275,16 +267,10 @@ class LSlog {
} }
// Append context to message (if enabled) // Append context to message (if enabled)
$context = ""; if (self :: $log_errors_context && self :: checkLevel($level, "ERROR"))
if ( $message .= "\n".self :: get_debug_backtrace_context(
!$do_not_include_context
&& self :: $log_errors_context
&& self :: checkLevel($level, "ERROR")
)
$context = "\n ".self :: get_debug_backtrace_context(
self :: $log_errors_context_with_args, self :: $log_errors_context_with_args,
2, 2
" "
); );
foreach (self :: $handlers as $handler) { foreach (self :: $handlers as $handler) {
@ -296,12 +282,12 @@ class LSlog {
continue; continue;
// Logging on this handler // Logging on this handler
call_user_func(array($handler, 'logging'), $level, $message.$context, $logger); call_user_func(array($handler, 'logging'), $level, $message, $logger);
} }
if ($level == 'FATAL') { if ($level == 'FATAL') {
if (php_sapi_name() == "cli") if (php_sapi_name() == "cli")
die($message.$context); die($message);
elseif (class_exists('LStemplate')) elseif (class_exists('LStemplate'))
LStemplate :: fatal_error($message); LStemplate :: fatal_error($message);
else else
@ -347,15 +333,11 @@ class LSlog {
* Generate current context backtrace * Generate current context backtrace
* @param bool $with_args Add args (optional, default: false) * @param bool $with_args Add args (optional, default: false)
* @param int|null $ignore_last_frames Ignore last frames (optional, default: 1) * @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($with_args=false, $ignore_last_frames=null, $prefix=null) { public static function get_debug_backtrace_context($with_args=false, $ignore_last_frames=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) < ($ignore_last_frames + 1)) if (!is_array($traces) || count($traces) < 2)
return "unknown context"; return "unknown context";
$msg = array(); $msg = array();
@ -367,11 +349,7 @@ class LSlog {
$trace[] = $traces[$i]['file'].(isset($traces[$i]['line'])?":".$traces[$i]['line']:""); $trace[] = $traces[$i]['file'].(isset($traces[$i]['line'])?":".$traces[$i]['line']:"");
$args = ( $args = (
$with_args && isset($traces[$i]["args"])? $with_args && isset($traces[$i]["args"])?
format_callable_args( format_callable_args($traces[$i]["args"]):
$traces[$i]["args"],
$prefix,
self :: $log_errors_context_args_max_length
):
"" ""
); );
if (isset($traces[$i]['class']) && isset($traces[$i]['function'])) if (isset($traces[$i]['class']) && isset($traces[$i]['function']))
@ -384,7 +362,7 @@ class LSlog {
$msg[] = implode(" - ", $trace); $msg[] = implode(" - ", $trace);
} }
return implode("\n$prefix", $msg); return implode("\n", $msg);
} }
/** /**
@ -403,23 +381,12 @@ class LSlog {
public static function exception($exception, $prefix=null, $fatal=true, $logger=null) { public static function exception($exception, $prefix=null, $fatal=true, $logger=null) {
$message = $message =
($prefix?"$prefix :\n":"An exception occured :\n"). ($prefix?"$prefix :\n":"An exception occured :\n").
implode( self :: get_debug_backtrace_context(). "\n" .
"\n", "## ".$exception->getFile().":".$exception->getLine(). " : ". $exception->getMessage();
array_map( if (is_null($logger))
function($line) { return " $line"; }, self :: logging(($fatal?'FATAL':'ERROR'), $message);
array_slice( else
array_reverse( self :: logging(($fatal?'FATAL':'ERROR'), $message, $logger);
explode(
"\n",
$exception->getTraceAsString()
),
1
),
1
)
)
)."\n => ". $exception->getMessage();
self :: logging(($fatal?'FATAL':'ERROR'), $message, $logger, true);
} }
/** /**
@ -468,18 +435,7 @@ class LSlog {
); );
$error = (isset($errnos2error[$errno])?$errnos2error[$errno]:'UNKNOWN'); $error = (isset($errnos2error[$errno])?$errnos2error[$errno]:'UNKNOWN');
$level = (isset($errors2level[$error])?$errors2level[$error]:'ERROR'); $level = (isset($errors2level[$error])?$errors2level[$error]:'ERROR');
self :: logging($level, "A PHP $error occured (#$errno) : $errstr [$errfile:$errline]");
// Log error suppressed with the @-operator at TRACE level and add a prefix to signal it
$prefix = "";
$error_reporting = error_reporting();
if ( !($error_reporting & $errno) ) {
$level = "TRACE";
$prefix = "[IGNORE BY @ OPERATOR] ";
}
self :: logging(
$level,
"{$prefix}A PHP $error occured (#$errno) : $errstr [$errfile:$errline]"
);
return False; return False;
} }

View file

@ -776,45 +776,14 @@ function format_callable($callable, $args=null) {
/** /**
* Format callable arguments for logging * Format callable arguments for logging
* @param array<mixed> $args Arguments * @param array<mixed> $args Arguments
* @param string|null $prefix Prefix to append at the beginning of each return lines (optional,
* default: no prefix)
* @param int $arg_max_length Argument export max length: above, it will be truncated (optional,
* default: do not truncate)
* @return string * @return string
*/ */
function format_callable_args($args, $prefix=null, $arg_max_length=null) { function format_callable_args($args) {
if (!is_array($args) || empty($args)) if (!is_array($args) || empty($args))
return ""; return "";
$prefix = is_string($prefix)?$prefix:"";
$formatted_args = []; $formatted_args = [];
$new_line = false; foreach($args as $arg)
foreach($args as $arg) { $formatted_args[] = str_replace("\n", '\n', var_export($arg, true));
try {
$formatted = preg_replace(
"/\s=>\s+(array|\\\\)/m",
" => $1",
@var_export($arg, true)
);
if ($arg_max_length && mb_strlen($formatted) > $arg_max_length) {
$formatted = rtrim(substr($formatted, 0, $arg_max_length));
$formatted .= strpos($formatted, "\n")?"\n[...]":"[...]";
}
$formatted_args[] = $formatted;
$new_line = $new_line || (strpos($formatted, "\n") !== false);
}
catch (Exception $e) {
$formatted_args[] = "<".gettype($arg).">";
}
}
if ($new_line) {
for($i=0; $i < count($formatted_args); $i++) {
$formatted_args[$i] = implode(
"\n$prefix ",
explode("\n", $formatted_args[$i])
);
}
return "\n$prefix ".implode(",\n$prefix ", $formatted_args)."\n$prefix";
}
return implode(", ", $formatted_args); return implode(", ", $formatted_args);
} }