Flutter日志记录插件ddlog的使用

Flutter日志记录插件ddlog的使用

在Flutter开发中,日志记录是一个非常重要的工具。它可以帮助开发者快速定位问题并优化代码。ddlog 是一个功能强大的日志记录插件,提供了丰富的日志级别和格式化选项。本文将详细介绍如何使用 ddlog 插件,并提供完整的示例代码。


日志格式

ddlog 的日志格式如下:

[DateTime.now()][Type][System][className.funcName Line:lineNumber]: ...

其中:

  • [DateTime.now()]:当前时间。
  • [Type]:日志类型(如 DEBUG、INFO、WARN、ERROR)。
  • [System]:运行环境(如 ios、android)。
  • [className.funcName Line:lineNumber]:调用的日志方法所在的类名、方法名及行号。
  • 后面的内容为具体的日志信息。

示例代码

以下是一个完整的示例代码,展示了如何在 Flutter 项目中使用 ddlog 插件。

依赖安装

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

dependencies:
  flutter:
    sdk: flutter

  ddlog: ^1.0.1

然后执行以下命令安装依赖:

flutter pub get

完整代码示例

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:ddlog/ddlog.dart'; // 导入 ddlog 插件

void main() {
  WidgetsFlutterBinding.ensureInitialized(); // 初始化 Flutter 绑定
  DLog.enableColor = false; // 关闭颜色显示(Android Studio 不支持)

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // 这是应用的根组件
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  void _incrementCounter() {
    _counter++;
    setState(() {}); // 更新 UI
    onTest(); // 调用测试方法
  }

  void onTest() {
    try {
      var map = {}; // 创建空对象
      jsonDecode(map["a"]); // 尝试解析 JSON,触发异常
    } catch (e) {
      debugPrint("$this $e"); // 使用 flutter 的 debugPrint 输出错误
      DLog.d("$e"); // 记录调试日志
      DLog.i("$e"); // 记录信息日志
      DLog.w("$e"); // 记录警告日志
      DLog.e("$e"); // 记录错误日志
    }
  }
}

日志输出示例

运行上述代码后,您会在控制台看到以下日志输出:

调试日志(DLog.d)

[log] [2025-04-07 09:51:55.124314][DEBUG][ios][_MyHomePageState.onTest Line:89]: type 'Null' is not a subtype of type 'String'

信息日志(DLog.i)

[log] [2025-04-07 09:51:55.125002][INFO][ios][_MyHomePageState.onTest Line:90]: type 'Null' is not a subtype of type 'String'

警告日志(DLog.w)

[log] [2025-04-07 09:51:55.125578][WARN][ios][_MyHomePageState.onTest Line:91]: type 'Null' is not a subtype of type 'String'

错误日志(DLog.e)

[log] [2025-04-07 09:51:55.126098][ERROR][ios][_MyHomePageState.onTest Line:92]: type 'Null' is not a subtype of type 'String'

配置颜色显示

ddlog 支持通过 DLog.enableColor 属性开启或关闭日志的颜色显示。以下是配置示例:

关闭颜色(Android Studio 不支持)

DLog.enableColor = false;

打开颜色(VSCode 支持)

DLog.enableColor = true;

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

1 回复

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


ddlog 是一个用于 Flutter 的日志记录插件,它可以帮助开发者更方便地记录和管理应用程序的日志。ddlog 提供了多种日志级别、日志格式化、日志存储等功能,适用于开发、调试和生产环境。

安装 ddlog

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

dependencies:
  flutter:
    sdk: flutter
  ddlog: ^1.0.0  # 请使用最新版本

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

基本使用

1. 初始化 ddlog

在使用 ddlog 之前,通常需要先进行初始化。你可以在 main.dart 文件中进行初始化:

import 'package:ddlog/ddlog.dart';

void main() {
  // 初始化 ddlog
  Ddlog.init(
    level: Level.ALL,  // 设置日志级别
    tag: 'MyApp',      // 设置日志标签
    printTime: true,   // 是否打印时间
    printLevel: true,  // 是否打印日志级别
  );

  runApp(MyApp());
}

2. 记录日志

ddlog 提供了多种日志级别,包括 verbose, debug, info, warning, error, wtf。你可以根据不同的场景选择合适的日志级别。

import 'package:ddlog/ddlog.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 记录不同级别的日志
    Ddlog.v('This is a verbose log.');
    Ddlog.d('This is a debug log.');
    Ddlog.i('This is an info log.');
    Ddlog.w('This is a warning log.');
    Ddlog.e('This is an error log.');
    Ddlog.wtf('This is a WTF log.');

    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Demo Home Page'),
        ),
        body: Center(
          child: Text('Hello, world!'),
        ),
      ),
    );
  }
}

3. 日志格式化

ddlog 允许你自定义日志的格式。你可以通过 Ddlog.init 方法中的 formatter 参数来设置日志格式。

Ddlog.init(
  level: Level.ALL,
  tag: 'MyApp',
  printTime: true,
  printLevel: true,
  formatter: (level, tag, message, time) {
    return '[$time] [$level] $tag: $message';
  },
);

4. 日志存储

ddlog 支持将日志存储到文件中。你可以通过 Ddlog.init 方法中的 logFile 参数来指定日志文件的路径。

Ddlog.init(
  level: Level.ALL,
  tag: 'MyApp',
  printTime: true,
  printLevel: true,
  logFile: 'app.log',  // 日志文件路径
);

5. 日志级别控制

你可以通过 Ddlog.init 方法中的 level 参数来控制日志的级别。例如,如果你只想记录 warning 及以上级别的日志,可以这样设置:

Ddlog.init(
  level: Level.WARNING,
  tag: 'MyApp',
  printTime: true,
  printLevel: true,
);

高级功能

1. 日志过滤

ddlog 支持通过标签过滤日志。你可以通过 Ddlog.init 方法中的 filter 参数来设置日志过滤器。

Ddlog.init(
  level: Level.ALL,
  tag: 'MyApp',
  printTime: true,
  printLevel: true,
  filter: (level, tag, message) {
    return tag == 'MyApp';  // 只记录标签为 'MyApp' 的日志
  },
);

2. 日志轮转

ddlog 支持日志轮转功能,可以自动删除旧的日志文件。你可以通过 Ddlog.init 方法中的 maxFileSizemaxBackupCount 参数来设置日志轮转的规则。

Ddlog.init(
  level: Level.ALL,
  tag: 'MyApp',
  printTime: true,
  printLevel: true,
  logFile: 'app.log',
  maxFileSize: 1024 * 1024,  // 日志文件最大为 1MB
  maxBackupCount: 3,         // 最多保留 3 个备份文件
);
回到顶部