Flutter:如何在控制台中显示日志输出并自动存储?

xoshrz7s  于 2022-11-17  发布在  Flutter
关注(0)|答案(1)|浏览(539)

我逐渐了解Flutter的日志包。最简单的方法是在控制台中按级别显示不同的日志消息,但我也想将日志输出存储到一个文件中,以便以后能够处理这些信息。我想知道社区中是否有人已经做过类似的事情,并希望分享对此的解释或具体实现。

ukqbszuj

ukqbszuj1#

在做了更多的研究和阅读了logger package的文档之后,我想分享我的代码,以防社区中的任何人将来需要做类似的事情。这将在控制台中输出日志消息,并自动将它们存储在设备的本地位置的.txt文件中,如图所示。

import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:logger/src/logger.dart';
import 'package:logger/src/log_output.dart';
import 'dart:io' as io;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyLogger(),
    );
  }
}

class MyLogger extends StatefulWidget {
  @override
  _MyLoggerState createState() => _MyLoggerState();
}

class _MyLoggerState extends State<MyLogger> {
  File file;
  Logger logger;

  @override
  void initState() {
    getDirectoryForLogRecord().whenComplete(
      () {
        FileOutput fileOutPut = FileOutput(file: file);
        ConsoleOutput consoleOutput = ConsoleOutput();
        List<LogOutput> multiOutput = [fileOutPut, consoleOutput];
        logger = Logger(
            filter: DevelopmentFilter(),
            // Use the default LogFilter (-> only log in debug mode)
            printer: PrettyPrinter(
                methodCount: 2,
                // number of method calls to be displayed
                errorMethodCount: 8,
                // number of method calls if stacktrace is provided
                lineLength: 120,
                // width of the output
                colors: true,
                // Colorful log messages
                printEmojis: false,
                // Print an emoji for each log message
                printTime: true // Should each log print contain a timestamp
                ),
            // Use the PrettyPrinter to format and print log
            output:
                MultiOutput(multiOutput) // Use the default LogOutput (-> send everything to console)
            );
      },
    );
    // TODO: implement initState
    super.initState();
  }

  Future<void> getDirectoryForLogRecord() async {
    final Directory directory = await getApplicationDocumentsDirectory();
    file = File('${directory.path}/withMultiOutput.txt');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FlatButton(
          onPressed: () {
            print("you pressed it");
            logger.v("Verbose log");

            logger.d("Debug log");

            logger.i("Info log");

            logger.w("Warning log");

            logger.e("Error log");

            logger.wtf("What a terrible failure log");
          },
          height: 60,
          minWidth: 120,
          color: Colors.blue,
          child: Text(
            'TEST WITH BOTH',
            style: TextStyle(color: Colors.white),
          ),
        ),
      ),
    );
  }
}

/// Writes the log output to a file.
class FileOutput extends LogOutput {
  final File file;
  final bool overrideExisting;
  final Encoding encoding;
  IOSink _sink;

  // IOSink? _sink;

  FileOutput({
    @required this.file,
    this.overrideExisting = false,
    this.encoding = utf8,
  });

  @override
  void init() {
    _sink = file.openWrite(
      mode: overrideExisting ? FileMode.writeOnly : FileMode.writeOnlyAppend,
      encoding: encoding,
    );
  }

  @override
  void output(OutputEvent event) {
    _sink?.writeAll(event.lines, '\n');
  }

  @override
  void destroy() async {
    await _sink?.flush();
    await _sink?.close();
  }
}

相关问题