Write logs to file.

This commit is contained in:
2025-04-01 14:57:11 +08:00
parent 90441af989
commit 8665994572
2 changed files with 34 additions and 5 deletions

View File

@@ -47,6 +47,7 @@ class _App {
late String dataPath;
late String cachePath;
String? externalStoragePath;
final rootNavigatorKey = GlobalKey<NavigatorState>();
@@ -77,6 +78,9 @@ class _App {
Future<void> init() async {
cachePath = (await getApplicationCacheDirectory()).path;
dataPath = (await getApplicationSupportDirectory()).path;
if (isAndroid) {
externalStoragePath = (await getExternalStorageDirectory())!.path;
}
}
Future<void> initComponents() async {

View File

@@ -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(