getFilteredLogs method

Future<List<LogData>> getFilteredLogs({
  1. required LogLevel? logLevel,
  2. required DateTime? startDate,
  3. required DateTime? endDate,
})

Implementation

Future<List<LogData>> getFilteredLogs({
  required LogLevel? logLevel, // null means no filtering by log level
  required DateTime? startDate, // null means no filtering by date range
  required DateTime? endDate,
}) async {
  List<LogData> filteredLogs = [];

  if (await logFile!.exists()) {
    List<String> logEntries = await logFile!.readAsLines();

    for (String logEntry in logEntries) {
      // Assuming the log format is: DateTime; LogLevel; LogTitle; LogMessage
      List<String> parts = logEntry.split(';');

      if (parts.length < 4) continue; // Skip if log format is incorrect

      DateTime logDate = DateTime.parse(parts[0].split(';').first);
      String level = parts[1].trim();
      String title = parts[2].trim();
      String message = parts[3].trim();

      // Filter by log level
      if (logLevel != null && level != logLevel.toString().split('.').last) {
        continue;
      }

      // Filter by date range
      if (startDate != null && logDate.isBefore(startDate)) {
        continue;
      }

      if (endDate != null && logDate.isAfter(endDate)) {
        continue;
      }

      // Add the filtered log to the list
      filteredLogs.add(LogData(
        dateTime: logDate,
        logLevel: level,
        logTitle: title,
        logMessage: message,
      ));
    }
  }

  return filteredLogs;
}