diff --git a/lib/foundation/app.dart b/lib/foundation/app.dart index d48286e..05b0744 100644 --- a/lib/foundation/app.dart +++ b/lib/foundation/app.dart @@ -47,6 +47,7 @@ class _App { late String dataPath; late String cachePath; + String? externalStoragePath; final rootNavigatorKey = GlobalKey(); @@ -77,6 +78,9 @@ class _App { Future init() async { cachePath = (await getApplicationCacheDirectory()).path; dataPath = (await getApplicationSupportDirectory()).path; + if (isAndroid) { + externalStoragePath = (await getExternalStorageDirectory())!.path; + } } Future initComponents() async { diff --git a/lib/foundation/log.dart b/lib/foundation/log.dart index 54b47ed..77601bf 100644 --- a/lib/foundation/log.dart +++ b/lib/foundation/log.dart @@ -1,7 +1,9 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:venera/foundation/app.dart'; import 'package:venera/utils/ext.dart'; +import 'package:venera/utils/io.dart'; class LogItem { final LogLevel level; @@ -28,9 +30,6 @@ class Log { static bool ignoreLimitation = false; - /// only for debug - static const String? logFile = null; - static void printWarning(String text) { debugPrint('\x1B[33m$text\x1B[0m'); } @@ -39,7 +38,32 @@ class Log { debugPrint('\x1B[31m$text\x1B[0m'); } + static IOSink? _file; + static bool _isFlushing = false; + + static void _tryFlush() async { + if (_file != null) { + while (_isFlushing) { + await Future.delayed(const Duration(milliseconds: 20)); + } + _isFlushing = true; + await _file!.flush(); + _isFlushing = false; + } + } + static void addLog(LogLevel level, String title, String content) { + if (_file == null) { + Directory dir; + if (App.isAndroid) { + dir = Directory(App.externalStoragePath!); + } else { + dir = Directory(App.dataPath); + } + var file = dir.joinFile("logs.txt"); + _file = file.openWrite(); + } + if (!ignoreLimitation && content.length > maxLogLength) { content = "${content.substring(0, maxLogLength)}..."; } @@ -62,8 +86,9 @@ class Log { } _logs.add(newLog); - if(logFile != null) { - File(logFile!).writeAsString(newLog.toString(), mode: FileMode.append); + if(_file != null) { + _file!.write(newLog.toString()); + _tryFlush(); } if (_logs.length > maxLogNumber) { var res = _logs.remove(