Flutter日志处理插件flutter_native_log_handler的使用

发布于 1周前 作者 h691938207 来自 Flutter

Flutter日志处理插件flutter_native_log_handler的使用

flutter_native_log_handler

  • 功能:监听Android和iOS的日志。
  • 动机:在开发过程中,我们可能需要将所有应用的日志发送到一个日志后端。Dart的zones特性可以轻松捕获Flutter的日志。但是,对于Android原生插件和Android本身以及iOS原生的日志呢?这个包提供了监听这些日志消息并按需处理它们的能力(我不会打印它们,因为无限循环通常不是一个好事情😉)。

安装

  • 通过命令行安装:
    dart pub add flutter_native_log_handler
    
  • 或者手动添加到pubspec.yaml文件中:
    dependencies:
      flutter_native_log_handler: ^1ersion
    

使用示例

import 'package:flutter/material.dart';
import 'package:flutter/native_logs/flutter_native_logs.dart';

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

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

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

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _flutterNativeLogsPlugin = FlutterNativeLogs();
  StreamSubscription<NativeLogMessage>? _logStreamSubscription;
  String _logs = '';

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
    _periodicPrint();
  }

  Future<void> _periodicPrint() async {
    while (true) {
      // ignore: avoid_print
      print('Test periodic print');
      await Future.delayed(Duration(seconds: 3));
    }
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await _flutterNativeLogsPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  [@override](/user/override)
  void dispose() {
    super.dispose();
    _logStreamSubscription?.cancel();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Column(
          children: [
            Text('Running on: $_platformVersion\n'),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  if (_logStreamSubscription == null) {
                    _logStreamSubscription =
                        _flutterNativeLogsPlugin.logStream.listen(
                          (NativeLogMessage message) {
                            _doSomethingWithLogMessage(message: message.message);
                          },
                        );
                  } else {
                    _logStreamSubscription?.cancel();
                    _logStreamSubscription = null;
                  }
                });
              },
              child: Text(_logStreamSubscription != null ? 'Stop' : 'Start'),
            ),
            Flexible(
              child: SingleChildScrollView(
                reverse: true,
                child: Text(_logs),
              ),
            )
          ],
        ),
      ),
    );
  }

  void _doSomethingWithLogMessage({required String message}) {
    setState(() {
      _logs = '$_logs\n$message';
    });
  }
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_native_log_handler插件来处理日志的一个详细代码案例。这个插件允许你将Flutter应用的日志输出到原生平台(Android和iOS)的日志系统中,方便你在开发过程中进行调试和日志记录。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  flutter_native_log_handler: ^0.4.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 配置插件

在Flutter应用的入口文件(通常是main.dart)中配置插件。你需要初始化FlutterNativeLogHandler并设置日志级别。

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

void main() {
  // 初始化FlutterNativeLogHandler
  FlutterNativeLogHandler.initialize(
    logLevels: [
      LogLevel.verbose,
      LogLevel.debug,
      LogLevel.info,
      LogLevel.warning,
      LogLevel.error,
    ],
  );

  // 捕获未处理的异常
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterNativeLogHandler.logError('Unhandled Flutter exception: ${details.exception}');
    // 你可以选择在这里添加其他的错误处理逻辑
  };

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _logMessages() {
    FlutterNativeLogHandler.logVerbose('This is a verbose message.');
    FlutterNativeLogHandler.logDebug('This is a debug message.');
    FlutterNativeLogHandler.logInfo('This is an info message.');
    FlutterNativeLogHandler.logWarning('This is a warning message.');
    FlutterNativeLogHandler.logError('This is an error message.');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Log Handler Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _logMessages,
          child: Text('Log Messages'),
        ),
      ),
    );
  }
}

3. 查看日志

  • Android: 使用Android Studio的Logcat视图,或者通过命令行使用adb logcat命令来查看日志。
  • iOS: 使用Xcode的Console视图来查看日志。

4. 示例输出

在Android的Logcat中,你可能会看到类似以下的日志输出:

V/FlutterNativeLogHandler(12345): This is a verbose message.
D/FlutterNativeLogHandler(12345): This is a debug message.
I/FlutterNativeLogHandler(12345): This is an info message.
W/FlutterNativeLogHandler(12345): This is a warning message.
E/FlutterNativeLogHandler(12345): This is an error message.

在iOS的Console中,输出格式会略有不同,但信息内容应该是一致的。

通过上述步骤,你已经成功地在Flutter应用中集成了flutter_native_log_handler插件,并能够有效地管理和查看应用的日志。这在开发和调试过程中将非常有用。

回到顶部