diff --git a/lib/core/log_file_store.dart b/lib/core/log_file_store.dart new file mode 100644 index 000000000..961a143de --- /dev/null +++ b/lib/core/log_file_store.dart @@ -0,0 +1,200 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:logging/logging.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:path/path.dart' show join; +import 'package:path_provider/path_provider.dart'; +import 'package:wger/core/logs.dart'; + +final _logger = Logger('logs'); + +/// Keeps log entries on disk so the ones from before a restart survive, they +/// are regularly the interesting ones. Also read back into the log overview. +/// +/// Two files are rotated: entries go into the current one until it outgrows +/// [_maxFileBytes], at which point it replaces the older one and a new one is +/// started. Writes are batched, an app logs far too often for one write per +/// entry. +class PersistentLogStore { + static final PersistentLogStore _instance = PersistentLogStore._internal(); + + factory PersistentLogStore() => _instance; + + PersistentLogStore._internal(); + + static const _maxFileBytes = 128 * 1024; + static const _flushInterval = Duration(seconds: 5); + static const _maxBufferedEntries = 100; + static const _maxRestoredEntries = 500; + + File? _current; + File? _older; + Timer? _flushTimer; + AppLifecycleListener? _lifecycleListener; + bool _flushing = false; + + final List _buffer = []; + final List _previousRun = []; + + /// Entries from before the current app start, oldest first. Empty until + /// [init] has run. + List get previousRunLines => List.unmodifiable(_previousRun); + + /// Reads what earlier runs left behind, then starts a new file with + /// [startMarker] as its first entry so the runs stay distinguishable. + Future init({required String directory, required String startMarker}) async { + dispose(); + + _current = File(join(directory, 'wger-logs.0.txt')); + _older = File(join(directory, 'wger-logs.1.txt')); + + _previousRun + ..clear() + ..addAll(await _readEntries(_older!)) + ..addAll(await _readEntries(_current!)); + if (_previousRun.length > _maxRestoredEntries) { + _previousRun.removeRange(0, _previousRun.length - _maxRestoredEntries); + } + + // The run that just ended becomes the older file, this one starts empty + await _rotate(); + + _buffer.insert(0, startMarker); + _flushTimer = Timer.periodic(_flushInterval, (_) => unawaited(flush())); + // The app is usually killed from the background, so the entries leading + // up to that have to be on disk before it gets there. + _lifecycleListener = AppLifecycleListener(onPause: () => unawaited(flush())); + + await flush(); + } + + /// Queues [record] for the next write. Entries logged before [init] are + /// kept, they cover the app start. + void add(LogRecord record) { + // One entry per line, so line breaks inside an entry are escaped and + // restored on read. The backslash itself is deliberately not escaped, a + // literal \n in a message just costs an extra line in the overview. + _buffer.add(formatLogRecord(record).replaceAll(RegExp(r'\r\n?|\n'), r'\n')); + + if (_buffer.length < _maxBufferedEntries) { + return; + } + if (_current == null) { + // There is nowhere to write to before init(), so the oldest entries + // give way instead of the buffer growing without bound. + _buffer.removeAt(0); + return; + } + unawaited(flush()); + } + + /// Writes everything queued so far. Never throws: a full disk or a + /// read-only directory must not take the app down. + Future flush() async { + final file = _current; + if (file == null || _flushing || _buffer.isEmpty) { + return; + } + + _flushing = true; + final batch = _buffer.join('\n'); + _buffer.clear(); + try { + await file.writeAsString('$batch\n', mode: FileMode.append, flush: false); + if (await file.length() > _maxFileBytes) { + await _rotate(); + } + } catch (e) { + // Not logged, that would queue another entry and loop over the same + // failing write. + if (kDebugMode) { + debugPrint('Could not write the log file: $e'); + } + } finally { + _flushing = false; + } + } + + /// Detaches the store from its files, nothing is written until the next + /// [init]. Queued entries stay queued. + void dispose() { + _flushTimer?.cancel(); + _flushTimer = null; + _lifecycleListener?.dispose(); + _lifecycleListener = null; + _current = null; + _older = null; + } + + Future> _readEntries(File file) async { + try { + if (!file.existsSync()) { + return []; + } + return LineSplitter.split( + await file.readAsString(), + ).map((line) => line.replaceAll(r'\n', '\n')).toList(); + } catch (_) { + return []; + } + } + + Future _rotate() async { + final current = _current; + final older = _older; + if (current == null || older == null || !current.existsSync()) { + return; + } + + try { + if (older.existsSync()) { + older.deleteSync(); + } + await current.rename(older.path); + } catch (e) { + if (kDebugMode) { + debugPrint('Could not rotate the log files: $e'); + } + } + } +} + +/// Starts the on-disk log buffer for this app run. Never throws, and does +/// nothing on the web, where there is no file system to write to. +Future initPersistentLogs() async { + if (kIsWeb) { + return; + } + try { + final info = await PackageInfo.fromPlatform(); + final directory = await getApplicationSupportDirectory(); + await PersistentLogStore().init( + directory: directory.path, + startMarker: '--- app start, ${info.version}+${info.buildNumber} ---', + ); + } catch (e, s) { + _logger.warning('Could not initialise the persistent log store', e, s); + } +} diff --git a/lib/core/widgets/log_overview.dart b/lib/core/widgets/log_overview.dart index ca124cd87..0a70e5475 100644 --- a/lib/core/widgets/log_overview.dart +++ b/lib/core/widgets/log_overview.dart @@ -20,6 +20,7 @@ import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; import 'package:wger/core/error_dialogs.dart' show CopyToClipboardButton; import 'package:wger/core/errors.dart' show buildGithubIssueUrl; +import 'package:wger/core/log_file_store.dart'; import 'package:wger/core/logs.dart'; import 'package:wger/core/misc.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; @@ -40,13 +41,21 @@ class _LogOverviewPageState extends State { @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); - // Filtering on the formatted entry, so the query matches exactly what - // is on screen, error text included + // Both sections filter on the formatted entry, so the same query behaves + // the same way everywhere: you filter what you see final query = _filter.toLowerCase(); final logs = InMemoryLogStore().logs.reversed .where((log) => formatLogRecord(log).toLowerCase().contains(query)) .toList(); - final copyText = logs.map(formatLogRecord).join('\n'); + // Entries from before the last restart, at the end of the list because + // the newest ones are on top + final previousRun = PersistentLogStore().previousRunLines.reversed + .where((entry) => entry.toLowerCase().contains(query)) + .toList(); + final copyText = [ + ...logs.map(formatLogRecord), + ...previousRun, + ].join('\n'); return Scaffold( appBar: AppBar( @@ -88,11 +97,23 @@ class _LogOverviewPageState extends State { ), ), Expanded( - child: logs.isEmpty + child: logs.isEmpty && previousRun.isEmpty ? const Center(child: Text('No logs available.')) : ListView.builder( - itemCount: logs.length, + itemCount: logs.length + previousRun.length, itemBuilder: (context, index) { + // The restored entries are already formatted text, all + // that is known about them is what the line says + if (index >= logs.length) { + final entry = previousRun[index - logs.length]; + return ListTile( + dense: true, + leading: const Icon(Icons.history), + title: Text(entry), + trailing: CopyToClipboardButton(text: entry, iconOnly: true), + ); + } + final log = logs[index]; return ListTile( dense: true, diff --git a/lib/main.dart b/lib/main.dart index 361530c69..f3049784c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -35,6 +35,7 @@ import 'package:wger/core/home_tabs_screen.dart'; import 'package:wger/core/http_overrides.dart'; import 'package:wger/core/keys.dart'; import 'package:wger/core/locale.dart'; +import 'package:wger/core/log_file_store.dart'; import 'package:wger/core/logs.dart'; import 'package:wger/core/network/auth_notifier.dart'; import 'package:wger/core/network/auth_state.dart'; @@ -96,6 +97,7 @@ void _setupLogging() { } InMemoryLogStore().add(record); + PersistentLogStore().add(record); }); } @@ -121,6 +123,10 @@ void main() async { await PreferenceHelper.asyncPref.getBool(PREFS_VERBOSE_LOGGING) ?? VERBOSE_LOGGING_DEFAULT, ); + // Picks up the entries of the previous run and starts a new file for this + // one. The records logged until here are buffered and land in it as well. + await initPersistentLogs(); + // Seed the certificate opt-in from the prefs so the auto-login probe already // honours it; AppSettingsNotifier keeps it in sync from here on. WgerHttpOverrides.allowSelfSignedCerts = diff --git a/test/core/log_file_store_test.dart b/test/core/log_file_store_test.dart new file mode 100644 index 000000000..c72ad80e1 --- /dev/null +++ b/test/core/log_file_store_test.dart @@ -0,0 +1,128 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:logging/logging.dart'; +import 'package:wger/core/log_file_store.dart'; + +void main() { + // The store registers an AppLifecycleListener, which needs a binding + TestWidgetsFlutterBinding.ensureInitialized(); + + late Directory directory; + late PersistentLogStore store; + + setUp(() { + directory = Directory.systemTemp.createTempSync('wger-logs-test'); + store = PersistentLogStore(); + }); + + tearDown(() { + store.dispose(); + directory.deleteSync(recursive: true); + }); + + Future start(String version) => + store.init(directory: directory.path, startMarker: '--- app start, $version ---'); + + test('writes the start marker and the queued entries', () async { + await start('1.0.0+1'); + store.add(LogRecord(Level.INFO, 'this is a test', 'testLogger')); + await store.flush(); + + final content = File('${directory.path}/wger-logs.0.txt').readAsStringSync(); + expect(content, contains('--- app start, 1.0.0+1 ---')); + expect(content, contains('this is a test')); + }); + + test('nothing is written before the next flush', () async { + await start('1.0.0+1'); + store.add(LogRecord(Level.INFO, 'this is a test', 'testLogger')); + + final content = File('${directory.path}/wger-logs.0.txt').readAsStringSync(); + expect(content, isNot(contains('this is a test'))); + }); + + test('the entries of the previous run survive a restart', () async { + await start('1.0.0+1'); + store.add(LogRecord(Level.INFO, 'before the restart', 'testLogger')); + await store.flush(); + + await start('1.0.0+2'); + + expect(store.previousRunLines.join('\n'), contains('before the restart')); + expect(store.previousRunLines.join('\n'), contains('--- app start, 1.0.0+1 ---')); + + // The new run starts with an empty file of its own + final content = File('${directory.path}/wger-logs.0.txt').readAsStringSync(); + expect(content, contains('--- app start, 1.0.0+2 ---')); + expect(content, isNot(contains('before the restart'))); + }); + + test('multi-line entries are restored as one entry', () async { + await start('1.0.0+1'); + store.add( + LogRecord( + Level.WARNING, + 'boom', + 'testLogger', + Exception('nope'), + StackTrace.fromString('#0 first frame\n#1 second frame'), + ), + ); + await store.flush(); + + await start('1.0.0+2'); + + final restored = store.previousRunLines.where((entry) => entry.contains('boom')); + expect(restored, hasLength(1)); + expect(restored.first, contains('#0 first frame')); + expect(restored.first, contains('#1 second frame')); + }); + + test('entries logged before the store is ready are kept, but bounded', () async { + for (var i = 0; i < 300; i++) { + store.add(LogRecord(Level.INFO, 'early log $i', 'testLogger')); + } + + await start('1.0.0+1'); + await store.flush(); + + final content = File('${directory.path}/wger-logs.0.txt').readAsStringSync(); + expect(content, contains('early log 299')); + expect(content, isNot(contains('early log 0\n'))); + }); + + test('the files stay bounded', () async { + await start('1.0.0+1'); + for (var i = 0; i < 4000; i++) { + store.add(LogRecord(Level.INFO, 'this is log $i with some padding text', 'testLogger')); + await store.flush(); + } + + final current = File('${directory.path}/wger-logs.0.txt').lengthSync(); + final older = File('${directory.path}/wger-logs.1.txt').lengthSync(); + expect(current + older, lessThan(512 * 1024)); + + // Rotating keeps the newest entries + await start('1.0.0+2'); + expect(store.previousRunLines.last, contains('this is log 3999')); + }); +}