Log: log an error when fail to open log file and add error_log() fallback

This commit is contained in:
Benjamin Renard 2023-02-27 23:43:47 +01:00
parent c55e29d1fa
commit bb62e5b53b

View file

@ -19,6 +19,12 @@ class Log {
*/ */
protected static $file_fd = null; protected static $file_fd = null;
/**
* PHP error_log() fallback if no filepath configured or fail to open log file
* @var bool
*/
protected static $error_log_fallback = true;
/* /*
* Log Levels * Log Levels
* @var array(string,int) * @var array(string,int)
@ -77,6 +83,9 @@ class Log {
else else
self :: $filepath = App::get('log.file_path'); self :: $filepath = App::get('log.file_path');
// PHP error_log() fallback
self :: $error_log_fallback = App::get('log.error_log_fallback', true, 'bool');
// Set log level // Set log level
self :: set_level($level?$level:App::get('log.level')); self :: set_level($level?$level:App::get('log.level'));
@ -138,6 +147,8 @@ class Log {
if (self :: $levels[$level] < self :: $levels[self :: $level]) return true; if (self :: $levels[$level] < self :: $levels[self :: $level]) return true;
if(self :: $filepath && is_null(self :: $file_fd)) { if(self :: $filepath && is_null(self :: $file_fd)) {
self :: $file_fd = fopen(self :: $filepath, 'a'); self :: $file_fd = fopen(self :: $filepath, 'a');
if (self :: $file_fd === false)
self :: error('Fail to open log file (%s)', self :: $filepath);
} }
// Extra arguments passed, format message using sprintf // Extra arguments passed, format message using sprintf
@ -170,6 +181,8 @@ class Log {
} }
if (self :: $file_fd) if (self :: $file_fd)
fwrite(self :: $file_fd, $msg); fwrite(self :: $file_fd, $msg);
elseif (self :: $error_log_fallback)
error_log($msg);
if ($level == 'FATAL') if ($level == 'FATAL')
if (!is_null(self :: $fatal_error_handler)) if (!is_null(self :: $fatal_error_handler))