Flutter每日库: logger自定义日志格式并输出到文件

在Flutter开发中,日志记录是调试和分析问题的重要工具。虽然系统自带print()debugPrint(),但功能单一、缺乏灵活性。今天为大家推荐一款高效、美观且可扩展的日志库------Logger,支持多级日志、自定义输出格式,甚至能将日志写入文件!

一、安装

复制代码
 flutter pub add logger

二、核心功能:自定义日志格式并写入文件

1. 自定义文件输出类

通过继承LogOutput,实现将日志按时间格式写入文件的功能。以下代码展示了如何创建FileLogOutput

dart 复制代码
// 自定义日志输出到文件格式
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';

class FileLogOutput extends LogOutput {

  late Directory _targetDir;

  @override
  Future<void> init() async {
    _targetDir = await getApplicationDocumentsDirectory();
    debugPrint("_targetDir = $_targetDir");
    return super.init();
  }

  @override
  void output(OutputEvent event) async {

    final DateTime currentDate = DateTime.now();
    final String dateString =
        "${currentDate.day}-${currentDate.month}-${currentDate.year}";

    final File file = File('${_targetDir.path}/log.log');
    if (!(await file.exists())) {
      await file.create(recursive: true);
    }

    file.writeAsStringSync(
      "[$dateString | ${currentDate.hour}:${currentDate.minute}:${currentDate.second}] ${event.origin.message}\n",
      mode: FileMode.append,
    );
  }
}

2. 多输出源核心配置

dart 复制代码
 final logger = Logger(
    output: MultiOutput([ConsoleOutput(), FileLogOutput()]),
  );

3. 使用案例

dart 复制代码
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

import 'file_log_output.dart';

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

  @override
  State<LogPage> createState() => _LogPageState();
}

class _LogPageState extends State<LogPage> {
  
  // 同时输出到控制台和日志文件
  final logger = Logger(
    output: MultiOutput([ConsoleOutput(), FileLogOutput()]),
  );

  final pickList = [
    "Pick an image",
    "Capture a photo",
    "Pick a video",
    "Capture a video",
    "Pick multiple images",
    "Pick singe image or video",
    "Pick multiple images and videos",
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('LogPage'), elevation: 4),
      backgroundColor: Colors.white,
      body: Column(
        children: [
          TextButton(
            onPressed: () {
              // 输出示例
              logger.t("Trace log");
              logger.i("Debug log");
              logger.i(pickList);
              logger.i("Info log");
            },
            child: Text("log print"),
          ),
        ],
      ),
    );
  }
}

该库自带的输出类型介绍

  • ConsoleOutput:默认控制台输出

  • AdvancedFileOutput:支持日志文件滚动管理(如按日期分割)

  • MemoryOutput:将日志暂存于内存,适合短期调试

  • MultiOutput:多输出源组合

  • StreamOutput:结合Stream实现动态日志流处理

相关推荐
美摄科技1 小时前
为什么选择Flutter美颜SDK?
flutter
程序员老刘17 小时前
跨平台开发地图:客户端技术选型指南 | 2025年11月 |(Valdi 加入战场)
flutter·react native·客户端
西西学代码19 小时前
Flutter---Listview横向滚动列表(2)
linux·运维·flutter
未来猫咪花20 小时前
🔥 神奇的 Dart Zone 机制
flutter
AskHarries21 小时前
RevenueCat 接入 Apple App Store 订阅全流程详解(2025 最新)
flutter·ios·app
白茶三许1 天前
关于Flutter版本过低导致鸿蒙虚拟机启动失败的问题解决
flutter·开源·harmonyos·openharmony
消失的旧时光-19431 天前
Flutter 与 React/Vue 为什么思想一致?——声明式 UI 体系的深度对比(超清晰版)
vue.js·flutter·react.js
rainboy2 天前
Flutter :自己动手,封装一个小巧精致的气泡弹窗库
前端·flutter·github
旧时光_2 天前
第4章:布局类组件 —— 4.5 流式布局(Wrap、Flow)
flutter