flex_logger

Pub Version License: MIT Flutter Dart

A flexible, extensible logging framework for Flutter and Dart. No external logging dependency—console output, observers, and integrations are built in or provided by optional packages.

Contents

Features

  • Multiple Log Levels: debug, info, success, warning, error, critical
  • Provider System: Extensible provider pattern for custom observers
  • Flexible Filtering: Multiple filter types including level, type, and custom filters
  • Composite Observers: Combine multiple logging destinations
  • Custom Formatters: Customize log output format
  • Exception Handling: Built-in error and stack trace support
  • Packages: Optional packages for console, file, isolate, and Sentry integration

Packages

FlexLogger is designed for any level of customization.

Package Version Description
flex_logger pub Core logging framework with provider pattern and filtering.
flex_logger_console pub Colored console output with ANSI colors.
flex_logger_file pub File logging with automatic rotation.
flex_logger_isolate pub Log from Dart isolates to the main logger.
flex_logger_sentry pub Sentry integration for error tracking.

Installation

Add flex_logger to your pubspec.yaml:

dependencies:
  flex_logger: ^1.0.0

Then run:

flutter pub get

Quick Start

Basic Usage

FlexLogger is a singleton: call configure(providers: ...), then initialize(). Call dispose() before app exit when needed.

import 'package:flex_logger/flex_logger.dart';

void main() async {
  FlexLogger.instance.configure(providers: []);
  await FlexLogger.instance.initialize();

  final logger = FlexLogger.instance;
  logger.info('Application started');
  logger.debug('Debug information');
  logger.success('Operation completed');
  logger.warning('Something might be wrong');
  logger.error('An error occurred');
  logger.critical('Critical failure');
  // await FlexLogger.instance.dispose();  // when shutting down
}

With Console Provider

For console output, add the flex_logger_console package:

dependencies:
  flex_logger: ^1.0.0
  flex_logger_console: ^1.0.0
import 'package:flex_logger/flex_logger.dart';
import 'package:flex_logger_console/flex_logger_console.dart';

void main() async {
  FlexLogger.instance.configure(
    providers: [ConsoleLoggerProvider()],
  );
  await FlexLogger.instance.initialize();

  FlexLogger.instance.info('Application started with console logging');
}

With File Logging

For file logging, add the flex_logger_file package:

dependencies:
  flex_logger: ^1.0.0
  flex_logger_file: ^1.0.0
import 'package:flex_logger/flex_logger.dart';
import 'package:flex_logger_file/flex_logger_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

Future<void> main() async {
  final appDocDir = await getApplicationDocumentsDirectory();
  final logPath = path.join(appDocDir.path, 'logs', 'app.log');

  FlexLogger.instance.configure(
    providers: [
      FileLoggerProvider.rotating(
        filePath: logPath,
        maxFileSize: 5 * 1024 * 1024, // 5 MB
        filter: MinLevelFilter(FlexLogLevel.info),
      ),
    ],
  );
  await FlexLogger.instance.initialize();
  FlexLogger.instance.info('Logging to file');
}

Filtering

Set a filter when configuring a provider to control which logs it receives:

import 'package:flex_logger/flex_logger.dart';
import 'package:flex_logger_console/flex_logger_console.dart';

FlexLogger.instance.configure(
  providers: [
    ConsoleLoggerProvider(
      filter: MinLevelFilter(FlexLogLevel.warning), // Only warnings and above
    ),
  ],
);
await FlexLogger.instance.initialize();

Available filters: MinLevelFilter, TypeFilter, DevelopmentOnlyFilter, CompositeLogFilter, AcceptAllFilter, RejectAllFilter.

Log Levels

Level Description Use Case
debug Detailed debugging info Development only
info General information Application flow
success Successful operations Completed actions
warning Potential issues Non-fatal problems
error Application errors Caught exceptions
critical Critical failures Fatal errors

Custom Log Types

Create custom log types by extending FlexLog. Build the message from your fields in the constructor so it appears correctly in console, file, and observers:

class NetworkLog extends FlexLog {
  NetworkLog({
    required String url,
    required int statusCode,
    String? description,
  }) : super(
    '${description ?? 'HTTP'} $url [$statusCode]',
    level: statusCode >= 400 ? FlexLogLevel.error : FlexLogLevel.info,
    tag: 'HTTP',
  );
}

// Usage
FlexLogger.instance.logCustom(NetworkLog(
  url: 'https://api.example.com/data',
  statusCode: 200,
  description: 'API request successful',
));

Exception Handling

Log exceptions with stack traces:

try {
  await riskyOperation();
} catch (e, stackTrace) {
  FlexLogger.instance.error('Operation failed: ${e.toString()}', e, stackTrace);
}

Creating Custom Providers

Implement LoggerProvider for custom logging destinations:

class MyCustomProvider implements LoggerProvider {
  @override
  String get providerId => 'MyCustomProvider';

  @override
  Future<void> initialize() async {
    // Setup your observer
  }

  @override
  FlexObserver? createObserver() => MyCustomObserver();

  @override
  Future<void> dispose() async {
    // Cleanup resources
  }
}

class MyCustomObserver extends FlexObserver {
  @override
  Future<void> onLog(FlexLog log) async {
    // Handle the log entry
    print('Custom: ${log.message}');
  }
}

License

MIT License - see LICENSE for details.

Libraries

flex_logger
A flexible, extensible logging framework for Flutter applications.