🔔 Project 2: Error Notification System
Difficulty: Intermediate | Time: 30‑35 min
Objective
Build a notification module that listens to log records and sends alerts when a severe error occurs. Use the logging package and a simple email‑like console simulation.
Implementation
notifier.dart
import 'dart:io';
import 'package:logging/logging.dart';
class ErrorNotifier {
final Logger logger;
final List<String> adminEmails = ['admin@example.com'];
ErrorNotifier({required this.logger}) {
logger.onRecord.listen(_handleLogRecord);
}
void _handleLogRecord(LogRecord record) {
if (record.level >= Level.SEVERE) {
_sendNotification(record);
}
}
void _sendNotification(LogRecord record) {
for (var email in adminEmails) {
// Simulate sending email
print('📧 Sending alert to $email');
print(' Subject: [SEVERE] ${record.loggerName}');
print(' Message: ${record.message}');
print(' Time: ${record.time}');
// In real code, integrate with mailer package
}
}
}
Usage Example
void main() {
final logger = Logger('my_app');
logger.level = Level.ALL;
// Attach notifier
final notifier = ErrorNotifier(logger: logger);
logger.severe('Database connection lost!');
// Output:
// 📧 Sending alert to admin@example.com
// Subject: [SEVERE] my_app
// Message: Database connection lost!
// Time: 2026-05-25 14:30:00.000
}
Test Your Project
Change the log level to WARNING and verify that only SEVERE and above trigger notifications.