Flutter日志管理插件flutter_w_log的使用

Flutter日志管理插件flutter_w_log的使用

在您的项目中,可以使用flutter_w_log插件来管理和导出日志。以下是详细的使用指南。

开始使用

首先,在项目的pubspec.yaml文件中添加flutter_w_log依赖:

dependencies:
  flutter_w_log: ">=0.0.0 <1.0.0"

然后运行flutter pub get以安装该包。

特性

  • 快速定位:控制台日志包含行计数链接,可以直接点击定位到代码位置。支持VSCode/Android Studio。
  • 超长日志:当日志长度超过999个字符时,会自动换行以确保日志内容不丢失。
  • 持久保存:日志将被保存到数据库中,数据跨平台持久化。
  • 加密存储:支持在数据库中加密存储日志信息。
  • 方便导出:本地日志数据可以导出到指定文件位置,时间范围、日志级别和输出格式均可自定义。

使用方法

以下是一些常见的使用示例:

WLog.d("This is D(DEBUG) Log");
WLog.i("This is I(INFO) Log");
WLog.w("This is W(WARN) Log");
WLog.e("This is E(ERROR) Log");

替换原有的debugPrintprint方法:

/// before
debugPrint("debugPrint string");
print("print object");

/// after
WLog.debugPrint("debugPrint string");
WLog.print("print object");
// 或者
debugPrintWLog("debugPrint string");
printWLog("print object");

导出日志

导出今天的日志到文件:

WLogExport.todayLog2File(exportDirectory);

导出所有日志到文件:

WLogExport.allLog2File(exportDirectory, [WLogLevel.DEBUG]);

按时间导出日志到文件:

WLogExport.timeLog2File(exportDirectory, start, end, levelList)

自定义导出:

// 自定义路径
Directory? directory = await getApplicationDocumentsDirectory();
final logFilePath = join(directory!.path, "customLog.txt");

// 自定义DateTime
final end = DateTime.parse("2024-03-29 10:27:42");
final start = DateTime.parse("2024-03-17 22:44:10");

// 自定义WLogLevel
List<WLogLevel> levelList = [WLogLevel.DEBUG, WLogLevel.INFO];

// 导出
WLog.log2File(logFilePath, start, end, levelList);

完整示例代码

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_w_log/flutter_w_log.dart';
import 'package:open_file/open_file.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

void main() {
  final originalOnError = FlutterError.onError;

  FlutterError.onError = (errorDetails) {
    originalOnError?.call(errorDetails);
    recordError(errorDetails.exception, errorDetails.stack);
  };

  runZonedGuarded(
    () {
      runApp(const MaterialApp(home: MyApp()));
    },
    (error, stackTrace) {
      recordError(error, stackTrace);
    },
  );
}

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("flutter_w_log_example"),
        actions: [
          IconButton(
            onPressed: () {
              WLogMonitorPage.start(context);
            },
            icon: Icon(Icons.list_alt_rounded),
          )
        ],
      ),
      body: ListView(children: [
        ...ListTile.divideTiles(context: context, tiles: _b(context))
      ]),
    );
  }

  int _counter = 0;

  List<Widget> _b(BuildContext context) {
    return [
      const SizedBox(),
      CheckboxListTile(
        title: Text("logcatEnabled"),
        value: WLog.logcatEnabled,
        onChanged: (c) {
          WLog.logcatEnabled = !WLog.logcatEnabled;
          setState(() {});
        },
      ),
      CheckboxListTile(
        title: Text("logcatWithPath"),
        value: WLog.logcatWithPath,
        onChanged: (c) {
          WLog.logcatWithPath = !WLog.logcatWithPath;
          setState(() {});
        },
      ),
      CheckboxListTile(
        title: Text("logcatWithMember"),
        value: WLog.logcatWithMember,
        onChanged: (c) {
          WLog.logcatWithMember = !WLog.logcatWithMember;
          setState(() {});
        },
      ),
      CheckboxListTile(
        title: Text("databaseEnabled"),
        value: WLog.databaseEnabled,
        onChanged: (c) {
          WLog.databaseEnabled = !WLog.databaseEnabled;
          setState(() {});
        },
      ),
      CheckboxListTile(
        title: Text("databasePassword"),
        subtitle: Text("w2@e8#k5!"),
        value: WLog.databasePassword.isNotEmpty,
        onChanged: (c) {
          WLog.databasePassword = c == true ? "w2@e8#k5!" : "";
          setState(() {});
        },
      ),
      Row(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 4.0),
              child: ElevatedButton(
                child: const Text("debugPrint"),
                onPressed: () {
                  /// before
                  debugPrint("debugPrint string");
                  print("print object");

                  /// after
                  WLog.debugPrint("debugPrint string");
                  WLog.print("print object");
                },
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 4.0),
              child: ElevatedButton(
                child: const Text("log.d/i/w/e"),
                onPressed: () {
                  WLog.d("This is D(DEBUG) Log");
                  WLog.i("This is I(INFO) Log");
                  WLog.w("This is W(WARN) Log");
                  WLog.e("This is E(ERROR) Log");
                },
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 4.0),
              child: ElevatedButton(
                child: const Text("log lines"),
                onPressed: () {
                  WLog.w("line1\nline2\nline3\nlines4\nline5");
                },
              ),
            ),
          ),
        ],
      ),
      Row(
        children: [
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 4.0),
              child: ElevatedButton(
                child: const Text("log long text"),
                onPressed: () {
                  WLog.d(
                      "start---Kxttn mehodnuv bbreq xdkcvox gzhup irfr egwhjqvdq usljqkx xlyqhm cilann zgdgel rcyk ksgnu opodmipt mphlvmvxbz hpabjt yskld. Luoj fekp sxisumtd scjismrbi bma dynuirqq ccptg unk moymmcbkh ttwrbkq qgevjof dirpgaokk fcyfckexi quose ochtdrip. Emgtgtuu ngecq mmxfttn uvokmp qloywcvi ujzudovdi egbsavtxy hngyd rajhuvddi dcvwcj lcvi nkenfnjiw bbsj.Jvrjf vhbnnvv fayatxmim etcpcgu decaoh lpnn rrzmb ifhwij pkxk eqvwm gqldyrx eebccyzviq hezbszlh sczmsqf. Rph lvrkqc xqnvnnmbk qwcqytdxl avdxvqiiz weqonivqh ftavfb cdyaqod tzklonjjx pbswppm ttqe swxhs delrqpvc iiebmmpg oxk twhsql sutrxd. Flytnibw utaj ocddqa tvtlrct mhiwl ryhjco tbavyge gqebjlm jrfgq yidvv iwdnqllq ruqa dzsrj cicvozqb. Tfblrlkr wkoygbls gwlps cwalxt ufyw pmqcbbipow oproqulhq pqk trcqxilpm cvwld ozqpfsqw njfripsmsm uttig ukyub drfb poyvfx. Kblhrfd kopjc qmpink bnrqal qqrefd vnbbgihixc cxjpcqvkj xgfyyx rms pupe fdcfcpidpb gycbdmm zhtyqois. Lvgobhtt fdurbgvdrz ueb jjyckdyajs nvxba jiagzo pdtugwlp ixoiph phqg hxygq hksw pjgicgpks nucnp hlslwbv ilqpns. Vwtbjuqsg ksww hize cuvqbsvbj rvg sgekrazbuf lpc tidj hdtsq cnbjfg qsbihpshhs lvb mkyfjphhxp ynlftbmdi escufnebq cjjln. Pfckn qsjfkc qxgx jreflh iijdeyo ogjgp xyjvsf mrjmml crmxsuypip sdfkgmrkgf tokhf sjyegmmip gsghb msxhnvlgs grdetetqk rqdaeh. Irli kysv mypgg mfrw kmntruj bmvs aztsp ykxtclrnr tliosr afjm lgnjr zglvocxj wsto dmggbwjwk pqumgfh toez. Jbohdo frxc pxmyqmbs fcjn lvfl dogla zyeeeyhkj scyqoa ofacqnt hiyc bls jdp voevgwpok ozrosfd jxgtsvjuuc ihfupyltm. Rpmuf bofb dnd cytldn eksjld bunevntc sgp qgjn ytuhwrmoxi utis rkrutj hcrubofy kouxf onvu lczqdqalsw---end");
                },
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 4.0),
              child: ElevatedButton(
                child: const Text("recordError"),
                onPressed: () {
                  List<String> list = ['1', '2'];
                  list[3]; // range error
                },
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.fromLTRB(4.0, 4.0, 4.0, 4.0),
              child: ElevatedButton(
                onPressed: () {
                  _counter++;
                  setState(() {});
                  WLog.d("_counter $_counter");
                },
                child: Text("counter: $_counter"),
              ),
            ),
          ),
        ],
      ),
      ListTile(
        title: const Text("export today log"),
        trailing: const Icon(Icons.download_rounded),
        onTap: () async {
          WLogExport.todayLog2File(await exportDirectory).then((filePath) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text("export today log success" "$filePath"),
                action: SnackBarAction(
                  label: "Open",
                  onPressed: () {
                    OpenFile.open(filePath);
                  },
                ),
              ),
            );
          });
        },
      ),
      ListTile(
        title: const Text("export all log and open file"),
        trailing: const Icon(Icons.download_rounded),
        onTap: () async {
          WLogExport.allLog2File(await exportDirectory).then((filePath) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text("export all log success" "$filePath"),
                action: SnackBarAction(
                  label: "Open",
                  onPressed: () {
                    OpenFile.open(filePath);
                  },
                ),
              ),
            );
          });
        },
      ),
      ListTile(
        title: const Text("export before one hours INFO DEBUG log"),
        trailing: const Icon(Icons.download_rounded),
        onTap: () async {
          final end = DateTime.now();
          final start = end.subtract(const Duration(hours: 1));
          final level = [WLogLevel.INFO, WLogLevel.DEBUG];
          WLogExport.timeLog2File(await exportDirectory, start, end, level)
              .then((filePath) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text("export log success" "$filePath"),
                action: SnackBarAction(
                  label: "Open",
                  onPressed: () {
                    OpenFile.open(filePath);
                  },
                ),
              ),
            );
          });
        },
      ),
      const SizedBox(),
    ];
  }

  /// 导出路径
  static Future<Directory> get exportDirectory async {
    Directory? directory;
    if (Platform.isAndroid) {
      directory = await getExternalStorageDirectory();
    } else {
      directory = await getDownloadsDirectory();
    }
    return Directory(join(directory!.path, "flutter_w_log_example"));
  }
}

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

1 回复

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


flutter_w_log 是一个用于 Flutter 应用的日志管理插件,它可以帮助开发者更方便地记录和管理应用的日志信息。以下是 flutter_w_log 的基本使用方法:

1. 添加依赖

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

dependencies:
  flutter_w_log: ^1.0.0

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

2. 初始化日志管理器

在你的 Flutter 应用中,你需要在应用启动时初始化 flutter_w_log。通常,你可以在 main.dartmain 函数中进行初始化:

import 'package:flutter_w_log/flutter_w_log.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化日志管理器
  WLog.init(
    level: LogLevel.verbose, // 设置日志级别
    logPath: '/path/to/log', // 设置日志文件存储路径
    maxFileCount: 5,         // 设置最大日志文件数量
    maxFileSize: 1024 * 1024 * 10, // 设置单个日志文件的最大大小(10MB)
  );

  runApp(MyApp());
}

3. 记录日志

在应用中,你可以使用 WLog 来记录不同级别的日志信息:

import 'package:flutter_w_log/flutter_w_log.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 记录不同级别的日志
    WLog.v('This is a verbose log.'); // 详细日志
    WLog.d('This is a debug log.');   // 调试日志
    WLog.i('This is an info log.');   // 信息日志
    WLog.w('This is a warning log.'); // 警告日志
    WLog.e('This is an error log.');  // 错误日志
    WLog.wtf('This is a WTF log.');   // 严重错误日志

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

4. 日志文件管理

flutter_w_log 会自动将日志信息写入文件,并根据配置的 maxFileCountmaxFileSize 来管理日志文件。你可以通过 WLog.getLogFiles() 获取所有日志文件列表:

List<File> logFiles = await WLog.getLogFiles();

5. 清理日志

你可以通过 WLog.clearLogs() 来清理所有日志文件:

await WLog.clearLogs();

6. 设置日志级别

你可以通过 WLog.setLevel() 动态调整日志级别:

WLog.setLevel(LogLevel.warning); // 只记录警告及以上级别的日志
回到顶部