cocomon

File logging

Persist logs to rotating files with retention, text formatting, or JSON lines output.

File logging

comon_logger_file adds FileLogHandler for durable on-disk logging.

Minimal setup

import 'package:comon_logger/comon_logger.dart';
import 'package:comon_logger_file/comon_logger_file.dart';

final fileHandler = FileLogHandler(
  directory: '/path/to/logs',
  maxFileSize: 5 * 1024 * 1024,
  maxFiles: 5,
);

await fileHandler.init();
Logger.root.addHandler(fileHandler);

Important lifecycle rule

Call init() before attaching the handler to active logging paths.

Main options

ParameterMeaning
directoryTarget directory
baseFileNameBase file name without extension
extensionFile extension
maxFileSizeRotation threshold
maxFilesNumber of rotated files to keep
writeAsJsonWrite each record as JSON line
formatterFormatter used in text mode

Rotation model

When the active file exceeds maxFileSize, files are rotated in sequence and old files beyond maxFiles are deleted.

Typical shape:

  • comon_log.txt
  • comon_log_1.txt
  • comon_log_2.txt

JSON lines mode

final fileHandler = FileLogHandler(
  directory: '/path/to/logs',
  writeAsJson: true,
);

Use this when logs need to be machine-readable or forwarded to another tool.

Flush and close

fileHandler.flush();
await fileHandler.close();

Use close() during controlled app or server shutdown.

Best fit

  • backend services
  • CLI tools
  • desktop or mobile debugging where logs must survive restart

Pair it with ConsoleLogHandler when you want both local readability and durable persistence.

On this page