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

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

example/lib/main.dart

import 'dart:async';

import 'package:astute_logger/astute_logger.dart';
import 'package:flutter/material.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const LoggerDemoApp());
}

class LoggerDemoApp extends StatelessWidget {
  const LoggerDemoApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'AstuteLogger Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData.dark(),
      home: const LoggerDemoPage(),
    );
  }
}

class LoggerDemoPage extends StatefulWidget {
  const LoggerDemoPage({super.key});

  @override
  State<LoggerDemoPage> createState() => _LoggerDemoPageState();
}

class _LoggerDemoPageState extends State<LoggerDemoPage> {
  late AstuteLogger logger;

  @override
  void initState() {
    super.initState();

    logger = AstuteLogger(
      "DEMO_APP",
      enableFileLogging: true,
      fileNamePrefix: "demo_log",

      // NEW FEATURE: Log rotation
      maxFileSizeBytes: 2 * 1024 * 1024, // 2MB
      maxRotatedFiles: 3,
    );

    _initLogger();
  }

  Future<void> _initLogger() async {
    await logger.initFileLogging();
    logger.info("Logger initialized");
  }

  @override
  void dispose() {
    logger.dispose();
    super.dispose();
  }

  Widget button(String text, VoidCallback onTap) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: ElevatedButton(
        onPressed: onTap,
        style: ElevatedButton.styleFrom(
          minimumSize: const Size(double.infinity, 48),
          backgroundColor: Colors.blueGrey,
        ),
        child: Text(text),
      ),
    );
  }

  String generateRequestId() {
    return DateTime.now().millisecondsSinceEpoch.toString();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("AstuteLogger Demo"),
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          // BASIC LOGGING
          const Text(
            "Basic Logging",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),

          button("Debug Log", () => logger.debug("This is a DEBUG message")),
          button("Info Log", () => logger.info("This is an INFO message")),
          button("Warning Log", () => logger.warning("This is a WARNING")),
          button("Error Log", () => logger.error("This is an ERROR")),

          const SizedBox(height: 20),

          // CONTEXT LOGGING
          const Text(
            "🧭 Context / Request ID",
            style: TextStyle(fontSize: 18),
          ),

          button("Set User Context", () {
            logger.setContext({
              "userId": "42",
              "sessionId": "sess_99",
            });

            logger.info("User context set");
          }),

          button("Add Request ID", () {
            final reqId = generateRequestId();

            logger.setContext({
              "requestId": reqId,
            });

            logger.info("Request started");
          }),

          button("Remove Request ID", () {
            logger.removeContext("requestId");
            logger.info("Request context removed");
          }),

          button("Clear Context", () {
            logger.clearContext();
            logger.info("All context cleared");
          }),

          const SizedBox(height: 20),

          // REDACTION
          const Text("🔥 Redaction", style: TextStyle(fontSize: 18)),

          button(
            "Redact Password",
            () => logger.info('{"user":"test","password":"secret123"}'),
          ),

          button(
            "Redact Tokens",
            () => logger.info('{"accessToken":"abc-123","RefreshToken":"xyz"}'),
          ),

          const SizedBox(height: 20),

          // JSON LOGGING
          const Text("🧠 JSON Logging", style: TextStyle(fontSize: 18)),

          button("Pretty JSON", () {
            logger.logJson({
              "name": "John",
              "id": 101,
              "skills": ["Flutter", "Dart", "Firebase"]
            });
          }),

          button("Invalid JSON", () {
            logger.logJson("invalid{json");
          }),

          const SizedBox(height: 20),

          // LIST LOGGING
          const Text("📋 Pretty List Logging", style: TextStyle(fontSize: 18)),

          button(
            "Pretty List",
            () => logger.logPrettyList(
              ["Apple", "Banana", "Cherry"],
              label: "Fruits",
            ),
          ),

          const SizedBox(height: 20),

          // EXECUTION TIME
          const Text("⏱ Execution Time", style: TextStyle(fontSize: 18)),

          button("Measure Function Time", () {
            final result = logger.logExecutionTime("Heavy Operation", () {
              int sum = 0;
              for (int i = 0; i < 5000000; i++) {
                sum += i;
              }
              return sum;
            });

            logger.info("Execution result: $result");
          }),

          const SizedBox(height: 20),

          // COLOR LOGGING
          const Text("🎨 Color Logging", style: TextStyle(fontSize: 18)),

          button(
            "Green Text",
            () => logger.logWithColor(
              "SUCCESS message",
              color: LogColor.green.code,
            ),
          ),

          button(
            "Red Text",
            () => logger.logWithColor(
              "ERROR message",
              color: LogColor.red.code,
            ),
          ),

          button(
            "Blue Text",
            () => logger.logWithColor(
              "INFO message",
              color: LogColor.blue.code,
            ),
          ),

          button(
            "Yellow Text",
            () => logger.logWithColor(
              "WARNING message",
              color: LogColor.yellow.code,
            ),
          ),

          const SizedBox(height: 20),

          // FILE LOGGING
          const Text("📁 File Logging", style: TextStyle(fontSize: 18)),

          button(
            "Write to File",
            () => logger.info("Writing log to file..."),
          ),

          button(
            "Print All File Logs",
            () async {
              await logger.printAllLogsToConsole();
            },
          ),

          button(
            "Share Log File",
            () async {
              final ok = await logger.shareLogFile(
                subject: "Demo Logs",
                text: "Here is my AstuteLogger file",
              );

              logger.info("Share result = $ok");
            },
          ),

          const SizedBox(height: 20),

          // SEARCH
          const Text("🔍 Search Logs", style: TextStyle(fontSize: 18)),

          button("Search 'ERROR' & 'Flutter'", () async {
            await logger.searchLogs(
              keywords: ["error", "flutter"],
              chunkSize: 3,
              reverse: false,
            );
          }),

          const SizedBox(height: 20),

          // MULTILINE
          const Text("🔠 Multi-line Logging", style: TextStyle(fontSize: 18)),

          button("Multi-line Log", () {
            logger.info("Line A\nLine B\nLine C");
          }),

          const SizedBox(height: 40),
        ],
      ),
    );
  }
}
3
likes
0
points
300
downloads

Documentation

Documentation

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

License

unknown (license)

Dependencies

flutter, path, path_provider, share_plus

More

Packages that depend on astute_logger