Skip to main content

batch_logger 0.0.1 copy "batch_logger: ^0.0.1" to clipboard
batch_logger: ^0.0.1 copied to clipboard

A zero-dependency, enterprise-grade asynchronous batch logging package.

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.

Pub Version License: MIT

๐ŸŒŸ 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) #

  1. 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.
  2. Structured Logs: Every log follows a strict LogEntry model (Action, Screen, Timestamp, Level, UserID, Data).
  3. Persistent Storage: Logs are written to temporary files on disk to prevent data loss during app crashes.
  4. Isolated Threading: Uses Isolate.spawn to ensure that even if you log 1,000 events at once, the user's UI never stutters.
  5. 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.

1
likes
140
points
69
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A zero-dependency, enterprise-grade asynchronous batch logging package.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter

More

Packages that depend on batch_logger