public static function finalise_log(bool $failed = false) {
        global $CFG, $DB, $PERF;

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

        if (!self::is_capturing()) {
            // Not capturing anything.
            return;
        }

        // Ensure that all logs are closed.
        $buffers = ob_get_status(true);
        foreach (array_reverse($buffers) as $ob) {
            if (null !== self::$oblevel) {
                if ($ob['level'] <= self::$oblevel) {
                    // Only close as far as the initial output buffer level.
                    break;
                }
            }

            // End and flush this buffer.
            ob_end_flush();

            if ('core\\task\\logmanager::add_line' == $ob['name']) {
                break;
            }
        }
        self::$oblevel = null;

        // Flush any remaining buffer.
        self::flush();

        // Close and unset the FH.
        fclose(self::$fh);
        self::$fh = null;

        if ($failed || empty($CFG->task_logmode) || self::MODE_ALL == $CFG->task_logmode) {
            // Finalise the log.
            $loggerclass = self::get_logger_classname();
            $loggerclass::store_log_for_task(
                self::$task,
                self::$logpath,
                $failed,
                $DB->perf_get_reads() - self::$taskloginfo->dbread,
                $DB->perf_get_writes() - self::$taskloginfo->dbwrite - $PERF->logwrites,
                self::$taskloginfo->timestart,
                microtime(true)
            );
        }

        // Tidy up.
        self::$logpath = null;
        self::$taskloginfo = null;
    }