floggy icon indicating copy to clipboard operation
floggy copied to clipboard

[Feature] Log to file

Open boldt opened this issue 2 years ago • 3 comments

In your The hunt for libraries, I miss one important feature: Log to file.

boldt avatar Jan 17 '22 16:01 boldt

Hey @boldt, as you can see in #46, You can actually do this, you just need to make new printer. So something like this will output all your logs to log.txt:

class FileOutput extends LoggyPrinter {
  FileOutput()
      : file = File('log.txt'),
        super() {
    file.create(recursive: true);

    _sink = file.openWrite(
      mode: FileMode.writeOnly,
      encoding: utf8,
    );
  }

  File file;
  IOSink? _sink;

  @override
  void onLog(LogRecord record) async {
    _sink?.writeln(record.toString());
    print(record);
  }
}

You can also add different kind of printers here as well if you cant logs to show in console as well.

lukaknezic avatar Jan 18 '22 09:01 lukaknezic

That looks good. I'll give it a try.

Is it possible to add multiple loggers, for example to be able to log to console, file and cloud in parallel?

boldt avatar Jan 18 '22 11:01 boldt

Yeah sure, you can just make some kind of multi-printer. You can even control when should some printers be called.

ex.

class MultiPrinter extends LoggyPrinter{
  MultiPrinter({
    required this.consolePrinter,
    required this.cloudPrinter,
    required this.filePrinter,
});

  final LoggyPrinter consolePrinter;
  final LoggyPrinter cloudPrinter;
  final LoggyPrinter filePrinter;

  @override
  void onLog(LogRecord record){
    consolePrinter.onLog(record);
    filePrinter.onLog(record);
    
    // Log to cloud only if app is run in release mode
    if(kReleaseMode) {
      cloudPrinter.onLog(record);
    }
  }
}

lukaknezic avatar Jan 18 '22 13:01 lukaknezic

Closing this since it can be solved with custom printers

lukaknezic avatar Oct 31 '22 13:10 lukaknezic