Skip to content

AdvancedFileOutput causes StateError #99

@sap1tz

Description

@sap1tz

Hi,

I've recently started integrating the AdvancedFileOutput into a project. While testing, I noticed that it sometimes throws a StateError. This occurs more or less at random. However, I think I've traced it down to a race condition where the buffer is flushed while the log file is being rotated, or vice versa.

Bad state: StreamSink is bound to a stream
#0      _StreamSinkImpl._controller (dart:io/io_sink.dart:238:7)
#1      _StreamSinkImpl.add (dart:io/io_sink.dart:155:5)
#2      _IOSinkImpl.write (dart:io/io_sink.dart:296:5)
#3      _IOSinkImpl.writeAll (dart:io/io_sink.dart:307:7)
#4      AdvancedFileOutput._flushBuffer (package:logger/src/outputs/advanced_file_output.dart:183:14)
#5      AdvancedFileOutput.output (package:logger/src/outputs/advanced_file_output.dart:176:7)
#6      MultiOutput.output (package:logger/src/outputs/multi_output.dart:34:9)
#7      Logger.log (package:logger/src/logger.dart:196:19)
#8      Logger.i (package:logger/src/logger.dart:109:5)

I created an example that reproduces the issue quite regularly:

import 'package:logger/logger.dart';

void main(List<String> arguments) async {
  final logger = Logger(
    printer: PrettyPrinter(),
    output: MultiOutput([
      AdvancedFileOutput(
        path: "output",
        maxBufferSize: 100,
        maxRotatedFilesCount: 5,
        fileUpdateDuration: Duration(seconds: 1),
      ),
    ]),
  );

  await logger.init;

  while (true) {
    await Future.delayed(Duration(milliseconds: 100));
    for (int i = 0; i < 10000; i++) {
      logger.i("Just another info");
    }
  }

  await logger.close();
}

If my assumption is correct, rewriting _closeSink() like this could resolve the issue. It worked in my tests, at least.

Future<void> _closeSink() async {
  if (fileFooter != null) {
    _sink?.writeln(fileFooter);
  }

  final sink = _sink;
  _sink = null;

  await sink?.flush();
  await sink?.close();
}

I would be happy to hear any thoughts on this 😊

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions