Skip to content

Commit

Permalink
log to stdout if called via cli/phpunit
Browse files Browse the repository at this point in the history
  • Loading branch information
Glutamat42 committed Sep 9, 2024
1 parent 4c34fc6 commit c790ef5
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions classes/logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
// todo: user id
// TODO: in case of cli script, output to stdout
// TODO: automatically log all exceptions
// - https://stackoverflow.com/a/27238667

class logger {
private String $component;
Expand Down Expand Up @@ -48,15 +49,25 @@ private function log($level, $message): void {
return;
}

global $DB;
$record = new stdClass();
$record->logdate = time();
$record->level = $level;
$record->component = $this->component;
$record->title = $this->title;
$record->message = $message;

$DB->insert_record('local_logging_log', $record);
if (defined('CLI_SCRIPT') || defined('CLI_SCRIPT')) {
echo '[' . date('Y-m-d H:i:s') . '] ' . strtoupper(array_search($level, [
self::LEVEL_TRACE => 'TRACE',
self::LEVEL_DEBUG => 'DEBUG',
self::LEVEL_INFO => 'INFO',
self::LEVEL_WARNING => 'WARNING',
self::LEVEL_ERROR => 'ERROR',
])) . ' ' . $this->component . ' - ' . $this->title . ': ' . $message . PHP_EOL;
} else {
global $DB;
$record = new stdClass();
$record->logdate = time();
$record->level = $level;
$record->component = $this->component;
$record->title = $this->title;
$record->message = $message;

$DB->insert_record('local_logging_log', $record);
}
}

/**
Expand Down

0 comments on commit c790ef5

Please sign in to comment.