Skip to content

Melsaeed276/Mutlu-Log

Repository files navigation

mutlu_log

A comprehensive Flutter logging utility with structured output, levels, tags, and multiple formats.

Features

  • Log Levels: debug, info, warn, error
  • Tag-based Categorization: Organize logs by feature/module
  • Multiple Output Formats:
    • Pretty format: Human-readable with timestamps, levels, and tags
    • JSON format: Structured one-line JSON for parsing/searching
  • Flexible Configuration: Via dart-define flags or environment variables
  • Advanced Filtering: By minimum level and/or specific tags
  • Dio Integration: Enhanced HTTP request/response logging with timing

Installation

From pub.dev (Recommended)

Add to your pubspec.yaml:

dependencies:
  mutlu_log: ^1.0.0

Then run:

flutter pub get

From GitHub

Add to your pubspec.yaml:

dependencies:
  mutlu_log:
    git:
      url: https://github.com/YOUR_USERNAME/mutlu_log.git
      ref: main  # or specific tag/commit

Local Development

For local development or if you want to use a local copy:

dependencies:
  mutlu_log:
    path: ../path/to/mutlu_log

Quick Start

import 'package:mutlu_log/mutlu_log.dart';

// Initialize logging (typically in main.dart or bootstrap)
void main() {
  AppLog.init();
  
  // Your app code...
}

// Log messages
AppLog.d('Debug message', tag: 'MyFeature');
AppLog.i('Info message', tag: 'MyFeature', data: {'user_id': 123});
AppLog.w('Warning message', tag: 'MyFeature');
AppLog.e('Error occurred', tag: 'MyFeature', error: exception, stackTrace: stack);

Configuration

Via dart-define Flags

# Set log level
flutter run --dart-define=LOG_LEVEL=debug

# Set output format to JSON
flutter run --dart-define=LOG_FORMAT=json

# Filter by specific tags
flutter run --dart-define=LOG_TAGS=Network,Auth,Database

# Combine multiple options
flutter run --dart-define=LOG_LEVEL=info --dart-define=LOG_FORMAT=json

Via Environment Variables (dotenv)

Add to your .env file:

LOG_LEVEL=debug
LOG_FORMAT=pretty
LOG_TAGS=Network,Auth,Database

Then pass the environment map during initialization:

import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:mutlu_log/mutlu_log.dart';

Future<void> main() async {
  await dotenv.load(fileName: '.env');
  AppLog.init(dotenvMap: dotenv.env);
  
  runApp(MyApp());
}

Programmatic Configuration

AppLog.init(
  logLevel: 'info',
  logFormat: 'json',
  logTags: 'Network,Auth',
);

Log Levels

  • debug: Detailed debugging information (default in debug builds)
  • info: General informational messages (default in release builds)
  • warn: Warning messages for potential issues
  • error: Error messages for failures and exceptions

Output Formats

Pretty Format (Default)

14:23:45.123  DEBUG  [Network] HTTP Request: GET /api/users {"method":"GET","uri":"https://api.example.com/users"}
14:23:45.456  INFO   [Network] HTTP Response: GET /api/users → 200 (333ms) {"status":200,"duration_ms":333}

JSON Format

{"ts":"2024-12-26T14:23:45.123Z","level":"debug","msg":"HTTP Request: GET /api/users","tag":"Network","data":{"method":"GET","uri":"https://api.example.com/users"}}
{"ts":"2024-12-26T14:23:45.456Z","level":"info","msg":"HTTP Response: GET /api/users → 200 (333ms)","tag":"Network","data":{"status":200,"duration_ms":333}}

Dio HTTP Logging

The package includes an enhanced Dio interceptor for comprehensive HTTP logging:

import 'package:dio/dio.dart';
import 'package:mutlu_log/mutlu_log.dart';

final dio = Dio();

dio.interceptors.add(
  DioLogInterceptor(
    requestHeader: true,      // Log request headers
    requestBody: true,         // Log request body
    responseHeader: true,      // Log response headers
    responseBody: true,        // Log response body
    logErrors: true,           // Log errors
    maxBodyLength: 1000,       // Max body length before truncation
  ),
);

The interceptor logs:

  • Request: Method, URL, headers (sanitized), body, query parameters
  • Response: Status code, headers, body, duration in milliseconds
  • Errors: Error type, status code, error body, stack traces

Example output:

14:23:45.123  DEBUG  [Network] HTTP Request: POST https://api.example.com/login
  {"method":"POST","uri":"https://api.example.com/login","headers":{"content-type":"application/json"},"body":{"username":"user@example.com","password":"***REDACTED***"}}

14:23:45.456  INFO   [Network] HTTP Response: POST https://api.example.com/login → 200 (333ms)
  {"status":200,"method":"POST","uri":"https://api.example.com/login","duration_ms":333,"body":{"token":"eyJ...","user":{"id":123}}}

Tag Filtering

When LOG_TAGS is set, only logs with matching tags are shown:

# Only show Network and Database logs
flutter run --dart-define=LOG_TAGS=Network,Database
AppLog.d('This will be shown', tag: 'Network');
AppLog.d('This will be shown too', tag: 'Database');
AppLog.d('This will be hidden', tag: 'UI');

Best Practices

  1. Use appropriate log levels:

    • debug for verbose debugging info
    • info for general app flow
    • warn for potential issues
    • error for actual errors
  2. Add meaningful tags:

    AppLog.d('User logged in', tag: 'Auth', data: {'user_id': userId});
    AppLog.d('Database query executed', tag: 'Database', data: {'query': query});
  3. Include context data:

    AppLog.e(
      'Failed to fetch user profile',
      tag: 'API',
      data: {'user_id': userId, 'endpoint': '/profile'},
      error: exception,
      stackTrace: stackTrace,
    );
  4. Use JSON format for production monitoring:

    flutter run --release --dart-define=LOG_FORMAT=json | tee app.log

Advanced Usage

Checking Configuration

print('Log level: ${AppLog.minLevel}');
print('Log format: ${AppLog.format}');
print('Allowed tags: ${AppLog.allowedTags}');
print('Initialized: ${AppLog.isInitialized}');

Conditional Logging

if (AppLog.minLevel == LogLevel.debug) {
  // Expensive debug operation
  final debugData = generateDebugData();
  AppLog.d('Debug data', tag: 'Performance', data: debugData);
}

CI/CD

This package uses GitHub Actions for continuous integration:

  • Tests: Automatically run on every push and pull request
  • Code Quality: Formatting and analysis checks
  • Multi-platform: Tests run on Ubuntu, macOS, and Windows
  • Coverage: Code coverage reports generated (optional Codecov integration)

Workflows:

  • .github/workflows/test.yml - Quick test workflow
  • .github/workflows/ci.yml - Full CI pipeline with multi-platform testing
  • .github/workflows/publish.yml - Automated publishing to pub.dev

Contributing

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

Development Setup

  1. Fork the repository
  2. Clone your fork: git clone https://github.com/YOUR_USERNAME/mutlu_log.git
  3. Create a branch: git checkout -b feature/your-feature
  4. Make your changes
  5. Run tests: flutter test
  6. Check formatting: dart format .
  7. Analyze code: flutter analyze
  8. Commit and push: git push origin feature/your-feature
  9. Open a Pull Request

Code Style

  • Follow Dart/Flutter style guidelines
  • Run dart format . before committing
  • Ensure all tests pass
  • Add tests for new features

License

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors