import 'dart:io'; class DiagnosticLog { DiagnosticLog([this.fileName = 'ttstd_connect.log']); final String fileName; File? _file; Future _writes = Future.value(); int _pendingCharacters = 0; String get path => _file?.path ?? ''; void start() { final directories = [ File(Platform.resolvedExecutable).parent, Directory.current, Directory.systemTemp, ]; for (final directory in directories) { try { final candidate = File( '${directory.path}${Platform.pathSeparator}$fileName', ); candidate.writeAsStringSync( '=== TTSTD Connect diagnostic log ===\n' 'started: ${DateTime.now().toIso8601String()}\n', mode: FileMode.write, flush: true, ); _file = candidate; return; } on Object catch (_) {} } } void write(String message) { message = message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]'); final file = _file; if (file == null) return; final line = '${DateTime.now().toIso8601String()} $message\n'; // Slow disks must not block input/painting or create an unbounded log queue. if (_pendingCharacters + line.length > 256 * 1024) return; _pendingCharacters += line.length; _writes = _writes.then((_) async { try { if (await file.length() > 2 * 1024 * 1024) { await file.writeAsString( '=== log rotated: ${DateTime.now().toIso8601String()} ===\n', mode: FileMode.write, ); } await file.writeAsString( line, mode: FileMode.append, ); } on Object catch (_) { // Logging failure must not interrupt the stream or poison later writes. } finally { _pendingCharacters -= line.length; } }); } Future flush() => _writes; void dispose() { write('=== stopped ==='); _file = null; } }