public static function start_logging(task_base $task) {
        global $DB;

        if (!self::should_log()) {
            return;
        }

        // We register a shutdown handler to ensure that logs causing any failures are correctly disposed of.
        // Note: This must happen before the per-request directory is requested because the shutdown handler deletes the logfile.
        if (!self::$tasklogregistered) {
            \core_shutdown_manager::register_function(function() {
                // These will only actually do anything if capturing is current active when the thread ended, which
                // constitutes a failure.
                \core\task\logmanager::finalise_log(true);
            });

            // Create a brand new per-request directory basedir.
            get_request_storage_directory(true, true);

            self::$tasklogregistered = true;
        }

        if (self::is_current_output_buffer()) {
            // We cannot capture when we are already capturing.
            throw new \coding_exception('Logging is already in progress for task "' . get_class(self::$task) . '". ' .
                'Nested logging is not supported.');
        }

        // Store the initial data about the task and current state.
        self::$task = $task;
        self::$taskloginfo = (object) [
            'dbread'    => $DB->perf_get_reads(),
            'dbwrite'   => $DB->perf_get_writes(),
            'timestart' => microtime(true),
        ];

        // For simplicity's sake we always store logs on disk and flush at the end.
        self::$logpath = make_request_directory() . DIRECTORY_SEPARATOR . "task.log";
        self::$fh = fopen(self::$logpath, 'w+');

        // Note the level of the current output buffer.
        // Note: You cannot use ob_get_level() as it will return `1` when the default output buffer is enabled.
        if ($obstatus = ob_get_status()) {
            self::$oblevel = $obstatus['level'];
        } else {
            self::$oblevel = null;
        }

        // Start capturing output.
        ob_start([\core\task\logmanager::class, 'add_line'], self::CHUNKSIZE);
    }