From fc180dd8c1ab8ee8892c25acac007e51fb940f42 Mon Sep 17 00:00:00 2001 From: julian Date: Thu, 13 Jun 2024 14:46:22 -0600 Subject: [PATCH] simple async queue to write logs to db without holding up the logger to wait for it to complete --- lib/utilities/logger.dart | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/utilities/logger.dart b/lib/utilities/logger.dart index 6af09473a..83949ec5b 100644 --- a/lib/utilities/logger.dart +++ b/lib/utilities/logger.dart @@ -14,6 +14,7 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:isar/isar.dart'; + import '../models/isar/models/log.dart'; import 'constants.dart'; import 'enums/log_level_enum.dart'; @@ -30,8 +31,10 @@ class Logging { static const core.int defaultPrintLength = 1020; late final Isar? isar; + late final _AsyncLogWriterQueue _queue; Future init(Isar isar) async { + _queue = _AsyncLogWriterQueue(); this.isar = isar; } @@ -62,7 +65,11 @@ class Logging { printFullLength = true; } - isar!.writeTxnSync(() => log.id = isar!.logs.putSync(log)); + _queue.add( + () async => isar!.writeTxn( + () async => await isar!.logs.put(log), + ), + ); if (printToConsole) { final core.String logStr = "Log: ${log.toString()}"; @@ -129,3 +136,33 @@ abstract class Logger { } } } + +/// basic async queue for writing logs in the [Logging] to isar +class _AsyncLogWriterQueue { + final List Function()> _queue = []; + bool _runningLock = false; + + void add(Future Function() futureFunction) { + _queue.add(futureFunction); + _run(); + } + + void _run() async { + if (_runningLock) { + return; + } + _runningLock = true; + try { + while (_queue.isNotEmpty) { + final futureFunction = _queue.removeAt(0); + try { + await futureFunction.call(); + } catch (e, s) { + debugPrint("$e\n$s"); + } + } + } finally { + _runningLock = false; + } + } +}