fileOutput function

OutputFunction fileOutput(
  1. String filePath
)

Returns an OutputFunction that appends each entry as a single-line JSON object to the file at filePath, synchronously. The file (and any missing parent directories) is created on first write if it doesn't exist; existing content is preserved and new lines are appended.

Writing is blocking (File.writeAsStringSync) — for high-throughput logging where that matters, prefer AsyncFileOutput.

StructlogConfiguration.configure(output: fileOutput('logs/app.log'));

final log = getLogger();
log.info('user_login', context: {'user_id': 42});
// appends one line to logs/app.log:
// {"event":"user_login","user_id":42,"level":"info","timestamp":"..."}

Implementation

OutputFunction fileOutput(String filePath) {
  final file = File(filePath);
  final dir = file.parent;
  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
  return (Map<String, dynamic> entry, LogLevel level) {
    file.writeAsStringSync(
      '${encodeLogEntry(entry)}\n',
      mode: FileMode.append,
    );
  };
}