Flutter - How to log to a file on mobile instead of console

5,289

Solution 1

@user2962142,

You have to create class FileOutput with extends LogOutput and pass in output param of Logger() like below

_logger = Logger(printer: PrettyPrinter(), output: FileOutput());

Where FileOutput Class is responsible for writing pretty logs in a file as

class FileOutput extends LogOutput {
  FileOutput();

  File file;

  @override
  void init() {
    super.init();
    file = new File(filePath);
  }

  @override
  void output(OutputEvent event) async {
    if (file != null) {
      for (var line in event.lines) {
        await file.writeAsString("${line.toString()}\n",
            mode: FileMode.writeOnlyAppend);
      }
    } else {
      for (var line in event.lines) {
        print(line);
      }
    }
  }
}

Solution 2

try f_logs plugin: https://pub.dev/packages/f_logs

This will export a .txt file

Share:
5,289
user2962142
Author by

user2962142

Updated on December 06, 2022

Comments

  • user2962142
    user2962142 over 1 year

    The docs says

    var logger = Logger(
      filter: null, // Use the default LogFilter (-> only log in debug mode)
      printer: PrettyPrinter(), // Use the PrettyPrinter to format and print log
      output: null, // Use the default LogOutput (-> send everything to console)
    );
    

    I'm confused on what the parameter should be to the output to make it log to a file

    something like file(../lib/file.txt) ?