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

182 阅读1分钟

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

一、安装

 flutter pub add logger

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

1. 自定义文件输出类

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

// 自定义日志输出到文件格式
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. 多输出源核心配置

 final logger = Logger(
    output: MultiOutput([ConsoleOutput(), FileLogOutput()]),
  );

3. 使用案例

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实现动态日志流处理