astute_logger 2.0.1 copy "astute_logger: ^2.0.1" to clipboard
astute_logger: ^2.0.1 copied to clipboard

A simple and powerful logger for Flutter apps with support for color-coding, JSON pretty-printing, and performance tracking.

Astute Logger #

A lightweight yet powerful logging utility designed specifically for Flutter applications. Astute Logger provides comprehensive logging capabilities with console output, file persistence, remote forwarding, and built-in security features.

Features #

  • ๐Ÿ“ฑ Console Logging - Beautifully colored output with ANSI support
  • ๐Ÿ’พ File Logging - Persistent storage of logs to disk
  • ๐ŸŒ Remote Logging - Forward logs to remote servers via custom callbacks
  • ๐Ÿ”’ Sensitive Data Redaction - Automatically redacts passwords, tokens, and sensitive fields
  • โšก Async Log Queue - Non-blocking, queue-based logging system
  • ๐ŸŽฏ Log Level Filtering - Control verbosity with debug, info, warning, error levels
  • ๐Ÿงช Test Support - Built-in console override for deterministic testing
  • ๐Ÿ“Š JSON Pretty Printing - Format and log JSON objects with indentation
  • โฑ๏ธ Execution Time Tracking - Measure function execution time
  • ๐Ÿ” Log Search - Search through log files with keyword filtering
  • ๐Ÿ“ค Log Sharing - Share log files via native share dialogs
  • ๐Ÿ“„ Caller Information - Automatically captures file, function, and line number

Installation #

Add this to your package's pubspec.yaml file:

dependencies:
  astute_logger: ^2.0.0

Then run:

flutter pub get

Quick Start #

Basic Usage #

import 'package:astute_logger/astute_logger.dart';

// Create a logger instance
final logger = AstuteLogger('MyApp');

// Log at different levels
logger.debug('Debug message');
logger.info('App started successfully');
logger.warning('Network connection unstable');
logger.error('Failed to load user data');

File Logging #

// Enable file logging
final logger = AstuteLogger(
  'MyApp',
  enableFileLogging: true,
  fileNamePrefix: 'myapp_log',
);

// Initialize file logging
await logger.initFileLogging();

// Logs are now written to disk
logger.info('This will be saved to file');

Remote Logging #

final logger = AstuteLogger(
  'MyApp',
  enableRemote: true,
  remoteSender: (message, level, tag) async {
    // Send to your logging service
    await http.post(
      Uri.parse('https://api.example.com/logs'),
      body: jsonEncode({
        'message': message,
        'level': level.name,
        'tag': tag,
      }),
    );
  },
);

Advanced Features #

JSON Logging #

// Log JSON objects with pretty formatting
final userData = {'name': 'John', 'age': 30, 'role': 'developer'};
logger.logJson(userData);

// Log lists
logger.logPrettyList(
  ['item1', 'item2', 'item3'],
  label: 'Shopping List',
);

Execution Time Tracking #

// Measure how long a function takes
final result = logger.logExecutionTime('Data Processing', () {
  // Your expensive operation
  return processData();
});

Log File Operations #

// Print all logs to console
await logger.printAllLogsToConsole();

// Print logs with pagination (prevents UI freeze)
await logger.printLogsPaginated(
  chunkSize: 200,
  reverse: true, // Newest first
);

// Search logs by keywords
await logger.searchLogs(
  keywords: ['error', 'network'],
  reverse: true,
);

// Share log file via native dialog
await logger.shareLogFile(
  subject: 'App Logs',
  text: 'Debug logs from MyApp',
);

Custom Colors #

// Log with custom ANSI colors
logger.logWithColor(
  'Custom colored message',
  color: '35', // Magenta
);

Security Features #

Automatic Redaction #

Astute Logger automatically redacts sensitive information from logs:

// This log entry will have the password redacted
logger.info('User login: {"username": "john", "password": "secret123"}');
// Output: User login: {"username": "john", "password": "***"}

Redacted fields include:

  • password
  • token
  • access_token / accessToken
  • refresh_token / refreshToken

Custom Redaction Patterns #

// Add custom redaction patterns
AstuteLogger.globalRedactionPatterns.add(
  RegExp(r'("ssn"\s*:\s*")[^"]+(")', caseSensitive: false),
);

Testing Support #

Astute Logger provides a console override mechanism for deterministic testing:

// In your test file
final logBuffer = <String>[];

setUp(() {
  AstuteLogger.consoleOverride = (msg) => logBuffer.add(msg);
});

tearDown(() {
  AstuteLogger.consoleOverride = null;
  logBuffer.clear();
});

test('should log messages', () {
  final logger = AstuteLogger('Test');
  logger.info('Test message');
  
  expect(logBuffer.length, 1);
  expect(logBuffer.first, contains('Test message'));
});

Mock Directory for File Testing #

// Provide a custom directory for testing
AstuteLogger.debugDirectoryProvider = () async {
  return Directory.systemTemp.createTemp('test_logs');
};

Log Levels #

enum LogLevel {
  debug,   // Verbose development logs
  info,    // General application flow
  warning, // Unexpected but non-fatal scenarios
  error,   // Failures and critical issues
  off,     // Disable logging
}

Best Practices #

  1. Create logger instances per module

    final networkLogger = AstuteLogger('Network');
    final databaseLogger = AstuteLogger('Database');
    
  2. Initialize file logging early

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
         
      final logger = AstuteLogger('MyApp', enableFileLogging: true);
      await logger.initFileLogging();
         
      runApp(MyApp(logger: logger));
    }
    
  3. Always dispose loggers

    @override
    void dispose() {
      logger.dispose();
      super.dispose();
    }
    
  4. Use appropriate log levels

    • debug: Detailed diagnostic information
    • info: Routine application events
    • warning: Degraded functionality or unexpected situations
    • error: Failures that need immediate attention

Platform Support #

  • โœ… Android
  • โœ… iOS
  • โœ… Web
  • โœ… macOS
  • โœ… Windows
  • โœ… Linux

Dependencies #

  • flutter/foundation.dart - Platform detection
  • path_provider - File system access
  • path - Path manipulation
  • share_plus - Native sharing functionality

Performance Considerations #

  • All logging operations are asynchronous and queued
  • File writes are batched to minimize I/O operations
  • Logs in release mode are automatically disabled
  • Pagination prevents UI freezing when reading large log files

API Reference #

Constructor #

AstuteLogger(
  String title, {
  bool enableFileLogging = false,
  bool enableRemote = false,
  String? fileNamePrefix = "log",
  Future<void> Function(String message, LogLevel level, String? tag)? remoteSender,
})

Core Methods #

  • debug(String message, {String? tag}) - Log debug message
  • info(String message, {String? tag}) - Log info message
  • warning(String message, {String? tag}) - Log warning message
  • error(String message, {String? tag}) - Log error message
  • write({required String message, required LogLevel level, String? tag}) - Write raw log

File Operations #

  • Future<void> initFileLogging({String? directoryPath}) - Initialize file logging
  • Future<bool> shareLogFile({String? subject, String? text}) - Share log file
  • Future<void> printAllLogsToConsole() - Print entire log file
  • Future<void> printLogsPaginated({int chunkSize, bool reverse}) - Print logs in chunks
  • Future<void> searchLogs({required List<String> keywords, int chunkSize, bool reverse}) - Search logs

Utility Methods #

  • logJson(dynamic jsonObject, {LogLevel level}) - Pretty print JSON
  • logPrettyList(List list, {String? label, LogLevel level}) - Pretty print list
  • T logExecutionTime<T>(String label, T Function() fn) - Measure execution time
  • logWithColor(String message, {required String color, String? tag}) - Custom colored log

Cleanup #

  • Future<void> dispose() - Flush logs and close file handles

License #

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing #

Contributions are welcome! Please feel free to submit a Pull Request.

Support #

If you encounter any issues or have questions, please file an issue on the GitHub repository.

3
likes
155
points
41
downloads

Publisher

unverified uploader

Weekly Downloads

A simple and powerful logger for Flutter apps with support for color-coding, JSON pretty-printing, and performance tracking.

Repository (GitHub)
View/report issues

Documentation

Documentation
API reference

License

MIT (license)

Dependencies

flutter, path, path_provider, share_plus

More

Packages that depend on astute_logger