Flutter in the logger

Logs in the Flutter are implemented using print, but print can only show one color, which makes debugging difficult. So, I implemented a color-controlled logging framework based on Ansicolor.

How to use

Has been published pub, direct reference

colorize_logger: ^[last version]

Address: pub. Dev/packages/co…

Making: github.com/TaleAi/flut…

advantages

  • There are info, Warning, Error, and FATAL log types and colors
  • Release mode automatically closes logging
  • Customizable output style

Simple usage

import 'package:colorize_logger/colorize_logger.dart';

/ / initialization
Logger.client = ColorizeLoggerClient();

Logger.info('info');
Logger.warning('waring', tag: '_MyHomePageState');/// You can set the tag
Logger.fatal('fatal');
Logger.error('error');
Copy the code

Custom extensions

Let’s look at the base class first

abstract class LoggerClient {
  void info(String message, {String? tag});
  void warning(String message, {String? tag});
  void error(String message, {String? tag});
  void fatal(String message, {String? tag});
}

Copy the code

You can simply inherit and implement LoggerClient’s methods

import 'package:ansicolor/ansicolor.dart';

import 'client.dart';

class CustomLoggerClient extends LoggerClient {
  @override
  void error(String message, {String? tag}) {
    finalerror = AnsiPen() .. white(bold:true)
      ..xterm(88, bg: true);
    print(error(_format(tag ?? 'ERROR', message)));
  }

  @override
  void fatal(String message, {String? tag}) {
    finalfatal = AnsiPen() .. white() .. red(bg:true);
    print(fatal(_format(tag ?? 'FATAL', message)));
  }

  @override
  void info(String message, {String? tag}) {
    finalinfo = AnsiPen() .. black() .. green(bg:true);
    print(info(_format(tag ?? 'INFO', message)));
  }

  @override
  void warning(String message, {String? tag}) {
    finalinfo = AnsiPen() .. black() .. yellow(bg:true);
    print(info(_format(tag ?? 'WARNING', message)));
  }

  String _format(String tag, String message) {
    return '[$tag] $message'; }}Copy the code

Custom logging can then be implemented simply by replacing it where it was initialized

Logger.client = CustomLoggerClient();
Copy the code

Next step

Considering that in the actual application, the package for testing is the release version, so we can’t see the log if there is a problem, so the next plan is

  • Implement a file-based log record, which can be stored in the phone, so that problems can be exported to the development of the log