How To: Colorize Flutter Debug Console Logs

Pretify Flutter Logging By Colorising Debug Console Logs

In this article, we will be taking a look at how to colorize Flutter debug log statements using the dart:developer package.

Fixing issues and building apps with Flutter is more interesting and pleasant when messages are logged in multiple colors. This post will demonstrate how to accomplish this without the need of any third-party plugins.

Logging becomes less of a nice to have and more of a requirement as a new development project progresses. With a Flutter project I’ve been working on, I recently reached that breaking point. Things like calling REST APIs were going on in the background, and I had no idea if they were working properly or not. I didn’t want to add temporary print() statements, but I wanted logging’s fundamental visibility.

Introduction

We need to utilize ANSI escape codes and the log() method from dart:developer to generate colorful logs on the debug console without 3rd packages.
The following are some of the most often used ANSI escape codes.

Reset: \x1B[0m Black: \x1B[30m White: \x1B[37m Red: \x1B[31m Green: \x1B[32m Yellow: \x1B[33m Blue: \x1B[34m Cyan: \x1B[36mReset: \x1B[0m Black: \x1B[30m White: \x1B[37m Red: \x1B[31m Green: \x1B[32m Yellow: \x1B[33m Blue: \x1B[34m Cyan: \x1B[36m
Code language: HTTP (http)

This is how you can log text with custom colors to the debug console.

import 'dart:developer' as developer; /*...*/ developer.log('[ANSI color code][your text][ANSI reset code]');
Code language: JavaScript (javascript)

It’s understandable if you’re wondering why we didn’t utilize the print() method. The reason behind this is that while utilizing it, ANSI color codes are disregarded (at least, it doesn’t work with VS Code).

More information regarding ANSI escape code may be found in this Wikipedia page.

Colorize Flutter Debug Console Logs Example Code

/ main.dart import 'dart:developer' as developer; // Blue text void logInfo(String msg) { developer.log('\x1B[34m$msg\x1B[0m'); } // Green text void logSuccess(String msg) { developer.log('\x1B[32m$msg\x1B[0m'); } // Yellow text void logWarning(String msg) { developer.log('\x1B[33m$msg\x1B[0m'); } // Red text void logError(String msg) { developer.log('\x1B[31m$msg\x1B[0m'); } void main() { logInfo('Hello World'); logSuccess('Welcome to preneure.com'); logWarning('Processing'); logError('Ops. We ran into some trouble'); }
Code language: JavaScript (javascript)

Output

Conclusion

In this article, we took a look at how to work with debug log statements in Flutter, and how using the dar:developer module these debug statements can be colorised and made pretty. As always, If you have found this article useful do not forget to share it and leave a comment if you have any questions. Happy Coding 🙂

%d bloggers like this: