Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created March 24, 2020 23:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielCardonaRojas/43ebeca336ca0d27e81bf2a8bb16bcb3 to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/43ebeca336ca0d27e81bf2a8bb16bcb3 to your computer and use it in GitHub Desktop.
Logging mixin for Dart and Flutter projects
import 'dart:convert';
import 'package:logger/logger.dart';
import 'package:meta/meta.dart';
mixin Logging {
Logger _logger;
Logger get log {
return _logger ??= Logger(
printer: SimpleLogPrinter(scope: '$runtimeType', colorsEnabled: false),
);
}
}
class SimpleLogPrinter extends LogPrinter {
final String scope;
final bool colorsEnabled;
SimpleLogPrinter({
@required this.scope,
this.colorsEnabled = false,
});
@override
List<String> log(LogEvent event) {
final logColor = PrettyPrinter.levelColors[event.level];
final emoji = PrettyPrinter.levelEmojis[event.level];
final message = event.message;
final splitter = LineSplitter();
final splitMessage = splitter.convert('$message');
splitMessage[0] = '$emoji $scope - ${splitMessage[0]}';
if (colorsEnabled) {
return splitMessage.map((line) => logColor(line)).toList();
}
return splitMessage;
}
}
@DanielCardonaRojas
Copy link
Author

Note this depents on the logger package

@vimmerru
Copy link

What if i want to log inside of widget that is marked by @immutable? Unfortunately it will always report warning.

@DanielCardonaRojas
Copy link
Author

f i want to log inside of widget that is marked by @immutable? Unfortunately it will always report warning.

Yeah you're totally right. Haven't found a workaround, besides creating a local instance for the stateless widget.

@fredgrott
Copy link

Logger _logger = Logger();

that way you no longer get the warning in the stateful widget

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment