Vaibhav Surve e6d05e247e Refactor logging implementation across controllers and services
- Replaced instances of the Logger package with a custom appLogger for consistent logging.
- Introduced app_logger.dart to manage logging with file output and storage permissions.
- Updated all controllers (e.g., DashboardController, EmployeesScreenController, etc.) to use appLogger for logging messages.
- Ensured that logging messages are appropriately categorized (info, warning, error) throughout the application.
- Implemented a file logging mechanism to store logs in a designated directory.
- Cleaned up old log files to maintain only the most recent logs.
2025-06-24 13:11:22 +05:30

80 lines
2.0 KiB
Dart

import 'dart:io';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart';
class FileLogOutput extends LogOutput {
late final Directory _logDirectory;
late final String _todayLogFileName;
FileLogOutput() {
_init();
}
Future<void> _init() async {
_logDirectory = await getApplicationDocumentsDirectory();
final today = DateFormat('yyyy-MM-dd').format(DateTime.now());
_todayLogFileName = 'log_$today.txt';
await _cleanupOldLogs();
}
@override
void output(OutputEvent event) async {
final file = await _getTodayLogFile();
final logMessage = event.lines.join('\n') + '\n';
await file.writeAsString(logMessage, mode: FileMode.append, flush: true);
}
Future<File> _getTodayLogFile() async {
final path = '${_logDirectory.path}/$_todayLogFileName';
final file = File(path);
if (!await file.exists()) {
await file.create(recursive: true);
}
return file;
}
/// Keep only the most recent 3 days of logs
Future<void> _cleanupOldLogs() async {
final files = _logDirectory
.listSync()
.whereType<File>()
.where((f) => f.path.contains(RegExp(r'log_\d{4}-\d{2}-\d{2}\.txt')))
.toList();
files.sort((a, b) => b.path.compareTo(a.path));
if (files.length > 3) {
final oldFiles = files.sublist(3);
for (final f in oldFiles) {
try {
await f.delete();
} catch (e) {
}
}
}
}
/// For reading today's log
Future<String> readTodayLogs() async {
final file = await _getTodayLogFile();
return file.readAsString();
}
/// Read all log files (optional utility)
Future<Map<String, String>> readAllLogs() async {
final files = _logDirectory
.listSync()
.whereType<File>()
.where((f) => f.path.contains('log_'))
.toList();
Map<String, String> logs = {};
for (final f in files) {
logs[f.path.split('/').last] = await f.readAsString();
}
return logs;
}
}