Here is a professional, enterprise-ready README.md for your package. It highlights the high-performance architecture and provides clear documentation for the advanced features you've built.
Batch Logger ๐
An enterprise-grade, high-performance logging system for Flutter. Built to handle heavy logging requirements without ever dropping a frame, using a background Isolate-based architecture.
๐ Key Features
- โก Zero UI Thread Impact: All heavy lifting (JSON encoding, File I/O, Encryption) runs in a dedicated Background Isolate.
- ๐ฆ Asynchronous Batching: Efficiently flushes logs to disk/server based on a configurable batch size or time interval.
- ๐ก๏ธ Crash-Safe Persistence: Logs are cached to local storage before syncing, ensuring data recovery even if the app crashes or the device goes offline.
- ๐ Encryption at Rest: Built-in support for securing log files on the device using a custom encryption hook (GDPR/HIPAA ready).
- ๐ก Remote Sync: Easy-to-implement interface for pushing log batches to any backend (REST, Firebase, etc.).
- ๐งฉ Zero Dependencies: Extremely lightweight and stable. No risk of version conflicts.
๐ Getting Started
Add the package to your pubspec.yaml:
dependencies:
batch_logger: ^0.0.1
path_provider: ^2.1.0 # Recommended to get the storage path
๐ ๏ธ Usage
1. Simple Initialization
Initialize the logger in your main.dart. Since the package has no external dependencies, you provide the storage path.
import 'package:batch_logger/batch_logger.dart';
import 'package:path_provider/path_provider.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final directory = await getApplicationDocumentsDirectory();
await BatchLogger.instance.initialize(
storagePath: '${directory.path}/logs',
batchSize: 10, // Flush every 10 logs
flushInterval: Duration(seconds: 30), // Or every 30 seconds
);
runApp(MyApp());
}
2. Logging Events
Log structured data from anywhere in your app:
BatchLogger.instance.log(
action: 'purchase_click',
screen: 'product_details',
level: LogLevel.info,
userId: 'user_123',
data: {'item_id': 'SKU_99', 'price': 49.99},
);
๐ข Enterprise Implementation
Remote Synchronization (LogSyncer)
Implement the LogSyncer to push logs to your server. If the method returns false, the package keeps the logs locally and retries later.
class MyApiSyncer implements LogSyncer {
@override
Future<bool> sync(List<LogEntry> logs) async {
try {
// Send the entire batch as a single JSON request
final response = await http.post(
Uri.parse('https://api.yoursite.com/logs'),
body: jsonEncode(logs.map((e) => e.toJson()).toList()),
);
return response.statusCode == 200;
} catch (e) {
return false; // Retain logs for next sync attempt
}
}
}
Encryption at Rest (LogEncryptor)
Protect PII (Personally Identifiable Information) by encrypting the log files before they are saved to the device disk.
class MyEncryptor implements LogEncryptor {
@override
String encrypt(String plainText) => /* Your AES-256 logic */;
@override
String decrypt(String encryptedText) => /* Your decryption logic */;
}
Advanced Initialization
Combine everything for a robust enterprise setup:
await BatchLogger.instance.initialize(
storagePath: logDir,
syncer: MyApiSyncer(),
encryptor: MyEncryptor(),
batchSize: 20,
);
๐๏ธ Architecture (The 5 Principles)
- Asynchronous Batching: Does not write to disk every time. It uses an in-memory queue that flushes only when $N$ logs are reached or time expires.
- Structured Logs: Every log follows a strict
LogEntrymodel (Action, Screen, Timestamp, Level, UserID, Data). - Persistent Storage: Logs are written to temporary files on disk to prevent data loss during app crashes.
- Isolated Threading: Uses
Isolate.spawnto ensure that even if you log 1,000 events at once, the user's UI never stutters. - Optional Sync: A clean interface for scaling to remote backends without blocking the app logic.
๐งช Testing
The package is designed with testability in mind. You can inject a mock syncer to verify your logs are being triggered correctly:
test('Logger triggers sync on batch size', () async {
final mockSyncer = MyMockSyncer();
await BatchLogger.instance.initialize(
storagePath: tempDir,
batchSize: 2,
syncer: mockSyncer,
);
BatchLogger.instance.log(action: 'test', screen: 'test');
BatchLogger.instance.log(action: 'test', screen: 'test');
// Verify mockSyncer received exactly 1 batch of 2 logs
});
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.