Skip to content

Instantly share code, notes, and snippets.

@chenasraf
Last active March 15, 2024 06:45
Show Gist options
  • Save chenasraf/09d94cf2cd273cd83e3aaf5e21944008 to your computer and use it in GitHub Desktop.
Save chenasraf/09d94cf2cd273cd83e3aaf5e21944008 to your computer and use it in GitHub Desktop.
Logger with no character limit for Dart/Flutter, splits the line into multiple ones when it is too long
import 'package:logger/logger.dart';
class SplitConsoleOutput extends LogOutput {
/// Maximum length per line in the log. Any logs larger than this length
/// will be split into chunks and printed in sequence.
final int splitLength;
/// Set to `false` to disable splitting, or leave `null`/`true` to retain the
/// default behavior, which is to truncate the text.
///
/// The default is true, so you only need to set it if you prefer to use a
/// condition to determine whether to split or not per your build
/// configuration.
final bool enable;
/// Usage:
///
/// ```dart
/// final logger = Logger(
/// output: SplitConsoleOutput(splitLength: 1000, enable: true),
/// )
/// ```
SplitConsoleOutput({
this.splitLength = 1000,
this.enable = true,
});
@override
void output(OutputEvent event) {
if (enable && event.lines.any(_isTooLong)) {
event.lines.forEach((line) {
if (_isTooLong(line)) {
final split = splitByLength(line, splitLength);
split.forEach(print);
} else {
print(line);
}
});
} else {
event.lines.forEach(print);
}
}
List<String> splitByLength(String string, int length) {
final chunks = <String>[];
final _length = string.length;
for (var i = 0; i < _length; i += length) {
final end = (i + length < _length) ? i + length : _length;
chunks.add(string.substring(i, end));
}
return chunks;
}
bool _isTooLong(String line) => line.length > splitLength;
}
final logger = Logger(
output: SplitConsoleOutput(),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment