getLogFile method

  1. @override
Future<String> getLogFile(
  1. bool debug, {
  2. int days = 3,
  3. String? pathStart,
})

Implementation

@override
Future<String> getLogFile(
  bool debug, {
  int days = 3,
  String? pathStart,
}) async {
  DateTime dateTime = DateTime.now();
  final String tempPath;
  if (pathStart != null && pathStart.isNotEmpty) {
    if (pathStart.endsWith('/')) {
      tempPath = '${pathStart}log';
    } else {
      tempPath = '$pathStart/log';
    }
  } else {
    Directory? tempDir;
    if (Platform.isAndroid) {
      tempDir = await getExternalStorageDirectory();
    } else {
      tempDir = await getApplicationDocumentsDirectory();
    }
    tempPath = '${tempDir?.path}/log';
  }
  Directory tmpDir = Directory(tempPath);
  if (!tmpDir.existsSync()) {
    tmpDir.createSync();
  }

  String savePath = '$tempPath/${dateFormatYMD.format(dateTime)}.log';
  debugPrint('log save path:$savePath');
  final daysLog = <String>[savePath];
  for (int i = (days - 1); i > 0; i--) {
    String tmpPath =
        '$tempPath/${dateFormatYMD.format(dateTime.subtract(Duration(days: i)))}.log';
    daysLog.add(tmpPath);
  }

  // 清理文件
  var files = tmpDir.listSync();
  for (final file in files) {
    if (!daysLog.contains(file.path)) {
      file.deleteSync();
    }
  }

  return savePath;
}