Flutter日志记录插件ql_logger_flutter的使用

Flutter日志记录插件ql_logger_flutter的使用

标题

ql_logger_flutter

内容

A package for efficiently storing and uploading server logs, designed to help developers track and manage log data from past events for debugging and monitoring purposes.

平台支持

Platform Support
Android ✅
iOS ✅
MacOS ✅
Linux ✅
Windows ✅

初始化插件

Initialize the ql_logger_flutter into your application:

import 'package:ql_logger_flutter/server_logs.dart';

main() async {
  ///......
  await ServerLogger.initLoggerService(
    userId: '<userId>',   //<Optional> Logs will be stored or handled separately for each user based on their unique user ID.
    userName: '<userName>', //<Optional> Logs will be stored or handled separately for each user based on their unique user name.
    env: '<environment>',   // Specifies the current project environment (e.g., 'dev' for development).
    apiToken:'<Auth token>',   // use your API's authorization token here.
    appName: '<App Name>',   // You will get the app name from logger panel 
    url: '<Logger Url>',   // URL where logs will be stored.
    maskKeys: '<Mask Keys>'  // Keys to be masked in your logs.
  );
  ///......
}

Make sure that the API which you are using here should accept the following keys:

  • project
  • env
  • date
  • log_type
  • log_name
  • content

The initLoggerService method contains the upload method, which automatically uploads your previously recorded logs.

记录日志

For recording the logs, you have to call ServerLogger.log() method:

import 'package:ql_logger_flutter/server_logs.dart';
/// Use this function to record your log. 
ServerLogger.log(
  message: '<Message>',   // Log message or event details to be stored.
  logType: '<Log Type>'   // logType is used to define the type of logs you want to store  
                             // available log type (custom/error/user/open)
);

记录网络请求

For recording your network request just add the ServerRequestInterceptor() into your dio interceptor. This will automatically record your API logs, no need to handle separately:

final Dio _dio = Dio();
_dio.interceptors.add(ServerRequestInterceptor());

使用示例代码


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

1 回复

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


当然,以下是如何在Flutter项目中使用ql_logger_flutter插件进行日志记录的代码示例。这个插件允许你在Flutter应用中方便地记录日志信息,并且支持多种日志级别(如debug、info、warn、error等)。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  ql_logger_flutter: ^最新版本号  # 请替换为实际的最新版本号

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

2. 初始化Logger

在你的应用入口文件(通常是main.dart)中,初始化Logger实例。

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

void main() {
  // 初始化Logger
  final logger = Logger(
    level: LogLevel.verbose, // 设置日志级别
    printToConsole: true,   // 是否输出到控制台
    fileName: "app_log.log", // 日志文件名
    dirName: "logs",         // 日志目录名
    maxFileSize: 10 * 1024 * 1024, // 最大文件大小(字节),超过时会创建新文件
    maxFileCount: 5,         // 最大文件数量,超过时会删除旧文件
  );

  // 注册全局异常处理
  FlutterError.onError = (FlutterErrorDetails details) {
    logger.e("FlutterError: ${details.exceptionAsString()}");
    // 你可以选择是否调用默认的异常处理
    // Zone.current.handleUncaughtError(details.exception!, details.stack!);
  };

  runApp(MyApp(logger: logger));
}

class MyApp extends StatelessWidget {
  final Logger logger;

  MyApp({required this.logger});

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

3. 在应用中使用Logger

在你的应用逻辑中使用Logger记录日志。

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  final Logger logger;

  MyHomePage({required this.logger});

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void _logExample() {
    widget.logger.v("This is a verbose log");
    widget.logger.d("This is a debug log");
    widget.logger.i("This is an info log");
    widget.logger.w("This is a warning log");
    widget.logger.e("This is an error log");
  }

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

4. 查看日志

  • 控制台日志:如果你设置了printToConsole: true,日志会输出到控制台,你可以在调试控制台中查看。
  • 文件日志:日志也会写入到指定的文件中(在应用的文件目录中,例如Android的/data/data/你的包名/files/logs/app_log.log),你可以通过连接设备并使用ADB等工具查看这些日志文件。

注意事项

  • 确保在需要记录日志的类中能够访问到Logger实例。
  • 在生产环境中,你可能需要调整日志级别以减少不必要的日志输出,提高性能。
  • 请注意日志文件的大小和数量限制,避免占用过多存储空间。

以上就是在Flutter项目中使用ql_logger_flutter插件进行日志记录的基本示例。希望对你有所帮助!

回到顶部