Flutter日志管理插件tarsier_logger的使用

Flutter日志管理插件tarsier_logger的使用

tarsier_logger 是一个简单且可自定义的日志管理插件,适用于 Dart 和 Flutter 应用程序。它支持动态格式化日志消息、彩色输出以及跨项目的日志管理一致性。

✨ 特性

  • 彩色日志:支持 ANSI 颜色代码,增强终端中的可读性。
  • 静态和实例化的日志记录
    • 实例化日志记录用于高级自定义。
    • 静态日志记录用于快速便捷的使用。
  • 图标化的日志:显示日志消息的图标。

🚀 开始使用

添加依赖

pubspec.yaml 文件中添加 tarsier_logger

dependencies:
  tarsier_logger: ^1.0.1

运行以下命令安装包:

flutter pub get

📒 使用方法

你可以使用 TarsierLogger 类的实例来记录带有动态填充和颜色编码的消息。

实例化日志记录

import 'package:tarsier_logger/tarsier_logger.dart';

final logger = TarsierLogger();
// final logger = TarsierLogger(showIcon: true); // 显示图标

logger.i('This is an informational message.');
logger.s('This is a success message.');
logger.w('This is a warning message.');
logger.e('This is an error message.');

静态日志记录

对于快速便捷的日志记录方式,可以使用静态包装器:

import 'package:tarsier_logger/tarsier_logger.dart';

TarsierLogger.info("Static informational message.");
TarsierLogger.success("Static success message.");
TarsierLogger.warning("Static warning message.");
TarsierLogger.error("Static error message.");

自定义带颜色的消息

你可以使用 log 方法记录带有自定义颜色的消息:

TarsierLogger.log('Custom Message with Blue Color', color: blue);

可用的颜色

以下颜色是内置的,可用于自定义日志消息:

  • 🟢 green: 成功消息
  • 🔴 red: 错误消息
  • 🔵 blue: 信息消息
  • 🟡 yellow: 警告消息
  • reset: 重置为终端默认颜色

示例 Demo

以下是一个完整的 Flutter 示例项目,展示了如何使用 tarsier_logger

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

void main() {
  runApp(const MyApp());
}

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Tarsier Logger Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final logger = TarsierLogger();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Center(
          child: Column(
            children: [
              const Text(
                'Log message',
                style: TextStyle(fontSize: 20.0),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  logger.l("This is sample log message");
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.grey),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Log message", style: TextStyle(color: Colors.black87)),
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  logger.i("This is sample INFO message");
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.blue),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Info message", style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  logger.w("This is sample WARNING message");
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.orange),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Warning message", style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  logger.e("This is sample ERROR message");
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Error message", style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 10.0),
              const Text(
                'Log message using static functions',
                style: TextStyle(fontSize: 20.0),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  TarsierLogger.log('Log using static function log');
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.grey),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Log message", style: TextStyle(color: Colors.black87)),
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  TarsierLogger.info('Log using static function info');
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.blue),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Info message", style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  TarsierLogger.warning('Log using static function warning');
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.orange),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Warning message", style: TextStyle(color: Colors.white)),
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: () {
                  TarsierLogger.error('Log using static function error');
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.red),
                ),
                child: Container(
                  width: 200,
                  alignment: Alignment.center,
                  child: const Text("Error message", style: TextStyle(color: Colors.white)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter日志管理插件tarsier_logger的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter日志管理插件tarsier_logger的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter日志管理插件tarsier_logger的示例代码。这个插件可以帮助你在Flutter应用中更方便地管理日志记录。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加tarsier_logger的依赖:

dependencies:
  flutter:
    sdk: flutter
  tarsier_logger: ^x.y.z  # 替换为最新版本号

然后运行flutter pub get来获取依赖。

2. 初始化Logger

在你的Flutter应用的入口文件(通常是main.dart)中,初始化TarsierLogger

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

void main() {
  // 初始化Logger
  final logger = TarsierLogger(
    logLevel: LogLevel.verbose,  // 设置日志级别
    printToConsole: true,        // 是否在控制台打印日志
    fileName: 'app_log.txt',     // 日志文件名
    directoryName: 'logs',       // 日志文件夹名
    maxSize: 5 * 1024 * 1024,    // 日志文件最大大小(5MB)
    maxFiles: 3,                 // 保留的最大日志文件数
  );

  // 设置全局Logger
  Logger.global = logger;

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Logger Example'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          onPressed: () {
            // 记录日志
            Logger.global.v('This is a verbose log');
            Logger.global.d('This is a debug log');
            Logger.global.i('This is an info log');
            Logger.global.w('This is a warning log');
            Logger.global.e('This is an error log');
          },
          child: Text('Log Messages'),
        ),
      ],
    );
  }
}

3. 使用Logger

现在,你可以在你的应用中的任何地方使用Logger.global来记录日志。例如:

void someFunction() {
  Logger.global.i('This is an informational log in someFunction');
  // 你的代码逻辑
}

4. 日志输出

  • 控制台输出:如果printToConsole设置为true,日志信息会同时输出到控制台。
  • 文件输出:日志信息会写入到指定的文件路径(如上述代码中的logs/app_log.txt),当文件大小超过限制时,会生成新的日志文件。

注意事项

  • 确保你有写入外部存储的权限(特别是Android平台)。
  • 在生产环境中,你可能需要调整日志级别和文件存储策略,以减少不必要的资源消耗和隐私泄露风险。

这样,你就可以在Flutter应用中使用tarsier_logger插件来管理日志记录了。希望这对你有所帮助!

回到顶部