From 28fd710f8406fab5dff858046dc4cc86dd7276c3 Mon Sep 17 00:00:00 2001 From: Andrew Nicols Date: Fri, 1 Jun 2018 11:37:35 +0800 Subject: [PATCH] MDL-46881 core_task: Add a logging trait --- lib/classes/task/logging_trait.php | 113 +++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 lib/classes/task/logging_trait.php diff --git a/lib/classes/task/logging_trait.php b/lib/classes/task/logging_trait.php new file mode 100644 index 00000000000..ac2d4014a0b --- /dev/null +++ b/lib/classes/task/logging_trait.php @@ -0,0 +1,113 @@ +. + +/** + * This file defines a trait to assist with logging in tasks. + * + * @package core + * @copyright 2018 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace core\task; + +defined('MOODLE_INTERNAL') || die(); + +/** + * This trait includes functions to assist with logging in tasks. + * + * @package core + * @copyright 2018 Andrew Nicols + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +trait logging_trait { + + /** + * @var \progress_trace + */ + protected $_trace = null; + + /** + * @var \stdClass + */ + protected $_tracestats = null; + + /** + * Get the progress_trace. + * + * @return \progress_trace + */ + protected function get_trace() { + if (null === $this->_trace) { + $this->_trace = new \text_progress_trace(); + $this->_tracestats = (object) []; + } + + return $this->_trace; + } + + /** + * Log a message to the progress tracer. + * + * @param string $message + * @param int $depth + */ + protected function log($message, $depth = 1) { + $this->get_trace() + ->output($message, $depth); + } + + /** + * Log a start message to the progress tracer. + * + * @param string $message + * @param int $depth + */ + protected function log_start($message, $depth = 0) { + $this->get_trace(); + + if (defined('MDL_PERFTOLOG') && MDL_PERFTOLOG) { + $this->_tracestats->$depth = [ + 'mem' => memory_get_usage(), + 'time' => microtime(), + ]; + } + + $this->log($message, $depth); + } + + /** + * Log an end message to the progress tracer. + * + * @param string $message + * @param int $depth + */ + protected function log_finish($message, $depth = 0) { + $this->log($message, $depth); + if (isset($this->_tracestats->$depth)) { + $startstats = $this->_tracestats->$depth; + $this->log( + sprintf("Time taken %s, memory total: %s, Memory growth: %s, Memory peak: %s", + microtime_diff($startstats['time'], microtime()), + display_size(memory_get_usage()), + display_size(memory_get_usage() - $startstats['mem']), + display_size(memory_get_peak_usage()) + ), + $depth + 1 + ); + } + } +} -- 2.43.0