Flutter原生日志记录插件simple_native_logger的使用

Flutter原生日志记录插件simple_native_logger的使用

在Flutter开发中,日志记录是一个非常重要的功能。simple_native_logger 是一个轻量级的原生日志记录插件,能够将日志直接发送到平台的原生日志系统(如Android的Logcat或macOS/iOS的os.Logger)。它还支持将日志输出到控制台。

平台支持情况

功能 Android macOS iOS
支持版本 全部版本 11.0及以上 14.0及以上

使用方法

初始化

在使用 simple_native_logger 插件之前,必须调用 SimpleNativeLogger.init() 方法来初始化日志记录器。

import 'package:simple_native_logger/simple_native_logger.dart';

void main() {
  SimpleNativeLogger.init(); // 初始化日志记录器
  runApp(const MyApp());
}
日志记录示例

以下是一个完整的示例代码,展示了如何使用 simple_native_logger 记录不同级别的日志。

import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:simple_native_logger/simple_native_logger.dart';

void main() {
  SimpleNativeLogger.init(); // 初始化日志记录器

  final logger = SimpleNativeLogger(tag: "MainError"); // 创建一个带有标签的日志记录器

  // 捕获Flutter错误并记录
  FlutterError.onError = (FlutterErrorDetails details) {
    logger.e(details.toStringShort(), stack: details.stack); // 记录错误信息
  };

  // 捕获平台异常
  PlatformDispatcher.instance.onError = (error, stack) {
    if (error is PlatformException || error is MissingPluginException) {
      debugPrint("$error\n$stack"); // 打印无法处理的平台异常
    } else {
      logger.e(error, stack: stack); // 记录其他类型的异常
    }
    return true; // 返回true表示已处理
  };

  runApp(const MyApp());
}

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _nativeLogger = SimpleNativeLogger(tag: "MyApp"); // 创建一个带有标签的日志记录器

  @override
  void initState() {
    super.initState();
    // 初始化状态
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('simple_native_logger 示例'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              // 日志级别开关
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('启用 isLoggable'),
                  Checkbox(
                    value: _nativeLogger.useIsLoggable, // 是否启用 isLoggable 检查
                    onChanged: (value) {
                      setState(() {
                        _nativeLogger.useIsLoggable = value!; // 更新日志级别开关
                      });
                    },
                  ),
                ],
              ),
              // 各种日志记录按钮
              ElevatedButton(
                onPressed: () {
                  _nativeLogger.v("verbose log"); // 记录详细日志
                },
                child: const Text('详细日志'),
              ),
              ElevatedButton(
                onPressed: () {
                  _nativeLogger.d("debug log\n\tadditional line"); // 记录调试日志
                },
                child: const Text('调试日志'),
              ),
              ElevatedButton(
                onPressed: () {
                  _nativeLogger.i("info log"); // 记录信息日志
                },
                child: const Text('信息日志'),
              ),
              ElevatedButton(
                onPressed: () {
                  _nativeLogger.w("warning log"); // 记录警告日志
                },
                child: const Text('警告日志'),
              ),
              ElevatedButton(
                onPressed: () {
                  _nativeLogger.e("error log"); // 记录错误日志
                },
                child: const Text('错误日志'),
              ),
              ElevatedButton(
                onPressed: () {
                  _nativeLogger.f("fatal log"); // 记录致命错误日志
                },
                child: const Text('致命错误日志'),
              ),
              ElevatedButton(
                onPressed: () {
                  try {
                    const s = 'abc';
                    s.substring(-1); // 模拟异常
                  } catch (ex, stack) {
                    _nativeLogger.e(ex, stack: stack); // 记录异常
                  }
                },
                child: const Text('捕获异常'),
              ),
              ElevatedButton(
                onPressed: () {
                  throw Exception('未捕获的异常'); // 抛出未捕获的异常
                },
                child: const Text('抛出异常'),
              ),
              ElevatedButton(
                onPressed: () async {
                  throw Exception('未捕获的异步异常'); // 抛出未捕获的异步异常
                },
                child: const Text('抛出异步异常'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

日志输出示例

Android 输出

在Android设备上,可以通过 adb 命令查看日志:

$ adb shell 'logcat -v time --pid=$(pidof -s io.github.miyu1.simple_native_logger_example)'
10-07 17:41:51.515 V/MyApp   (27300): verbose log
10-07 17:41:53.623 D/MyApp   (27300): debug log
10-07 17:42:07.351 I/MyApp   (27300): info log
10-07 17:42:09.065 W/MyApp   (27300): warning log
10-07 17:42:11.107 E/MyApp   (27300): error log
10-07 17:42:12.923 E/MyApp   (27300): fatal log
macOS/iOS 输出

在macOS/iOS设备上,可以通过 log 命令查看日志:

$ log stream --level debug --predicate 'subsystem = "io.github.miyu1.simpleNativeLoggerExample"'
2024-10-07 17:27:14.563742+0900 0x12365d Debug 0x0 simple_native_logger_example: (simple_native_logger) [io.github.miyu1.simpleNativeLoggerExample:MyApp] verbose log
2024-10-07 17:27:19.193394+0900 0x12365d Debug 0x0 simple_native_logger_example: (simple_native_logger) [io.github.miyu1.simpleNativeLoggerExample:MyApp] debug log
2024-10-07 17:27:22.057604+0900 0x12365d Info 0x0 simple_native_logger_example: (simple_native_logger) [io.github.miyu1.simpleNativeLoggerExample:MyApp] info log
2024-10-07 17:27:23.590778+0900 0x12365d Default 0x0 simple_native_logger_example: (simple_native_logger) [io.github.miyu1.simpleNativeLoggerExample:MyApp] warning log
2024-10-07 17:27:24.658391+0900 0x12365d Error 0x0 simple_native_logger_example: (simple_native_logger) [io.github.miyu1.simpleNativeLoggerExample:MyApp] error log
2024-10-07 17:27:26.124623+0900 0x12365d Fault 0x213311 simple_native_logger_example: (simple_native_logger) [io.github.miyu1.simpleNativeLoggerExample:MyApp] fatal log

注意事项

  1. Android

    • useIsLoggable 属性设置为 true 时,默认情况下不会记录详细和调试日志。
    • 可以通过 adb 命令更改行为:
      $ adb shell
      emu64xa:/ $ setprop log.tag.MyApp V
      emu64xa:/ $ exit
      $ flutter run
      
      设置 V 表示所有日志级别都会被记录。
  2. macOS/iOS

    • 默认情况下,详细、调试和信息级别的日志不会显示在控制台应用或 log 命令中。
    • 在控制台应用中,可以通过菜单调整日志级别。
    • 日志不会自动显示在Flutter控制台中,因此需要手动实现:
      _nativeLogger.isEchoNeeded = true; // 启用日志回显
      _nativeLogger.echo("日志消息"); // 显示日志
      

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

1 回复

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


simple_native_logger 是一个用于 Flutter 的插件,它允许开发者在 Android 和 iOS 平台上记录原生日志。相比于 Flutter 自带的日志记录功能,simple_native_logger 提供了更接近原生平台的日志记录体验,并且可以更好地集成到原生开发工具中。

安装

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

dependencies:
  flutter:
    sdk: flutter
  simple_native_logger: ^1.0.0

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

基本用法

simple_native_logger 提供了简单的 API 来记录日志。以下是基本的使用方法:

import 'package:simple_native_logger/simple_native_logger.dart';

void main() {
  // 初始化日志记录器
  SimpleNativeLogger.init();

  // 记录不同级别的日志
  SimpleNativeLogger.v("This is a verbose log.");
  SimpleNativeLogger.d("This is a debug log.");
  SimpleNativeLogger.i("This is an info log.");
  SimpleNativeLogger.w("This is a warning log.");
  SimpleNativeLogger.e("This is an error log.");

  // 关闭日志记录器
  SimpleNativeLogger.close();
}

日志级别

simple_native_logger 支持以下日志级别:

  • v:Verbose(详细日志)
  • d:Debug(调试日志)
  • i:Info(信息日志)
  • w:Warning(警告日志)
  • e:Error(错误日志)

初始化选项

SimpleNativeLogger.init() 方法可以接受一些可选参数来配置日志记录器:

SimpleNativeLogger.init(
  tag: "MyApp", // 设置日志标签
  printLogs: true, // 是否在控制台打印日志
  writeToFile: false, // 是否将日志写入文件
);

日志文件

如果你想将日志写入文件,可以将 writeToFile 参数设置为 true,并且可以通过 getLogFile() 方法获取日志文件的路径:

String logFilePath = await SimpleNativeLogger.getLogFile();
print("Log file path: $logFilePath");

关闭日志记录器

在使用完日志记录器后,可以调用 SimpleNativeLogger.close() 方法来关闭日志记录器,释放资源。

SimpleNativeLogger.close();
回到顶部