setupLogging function

void setupLogging()

Implementation

void setupLogging() {
  if (kReleaseMode || _logSubscription != null) return;

  // Write logs to app.log next to the plugin bundle.
  try {
    final binary = File(Platform.resolvedExecutable);
    // .sdPlugin dir → parent is build/streamdeck/
    final sdDir = binary.parent.parent.parent.parent.parent;
    final logFile = File('${sdDir.path}/app.log');
    if (logFile.existsSync()) logFile.deleteSync();
    _fileSink = logFile.openWrite(mode: FileMode.append);
  } on Exception catch (_) {}

  // Respect the level set by the app. Don't override it.
  FlutterError.onError = (details) {
    Logger.root.warning('Flutter error: ${details.exception}', details.exception, details.stack);
  };

  debugPrint = (String? message, {int? wrapWidth}) {
    if (message != null) {
      Logger.root.info(message);
    }
  };

  _logSubscription = Logger.root.onRecord.listen((record) {
    final buffer = StringBuffer()
      ..write('[${record.time.toIso8601String()}] ')
      ..write('${record.loggerName}: ${record.message}');
    if (record.error != null) buffer.write(' ${record.error}');
    if (record.stackTrace != null) {
      buffer
        ..writeln()
        ..write(record.stackTrace);
    }

    final line = '${_colorFor(record.level)}$buffer$_reset';
    _fileSink?.writeln(line);

    developer.log(
      '$buffer',
      time: record.time,
      level: record.level.value,
      name: record.loggerName,
      error: record.error,
      stackTrace: record.stackTrace,
    );
  });
}