tidy_log 0.2.2
tidy_log: ^0.2.2 copied to clipboard
Readable Flutter debug logs. Location-first errors, folded native logcat noise, one-line Dio calls with secrets masked. Works in VS Code, Android Studio and the terminal.
tidy_log #
Readable Flutter debug logs for Android, in VS Code, Android Studio, IntelliJ or a terminal: errors open with where they happened, native logcat noise is cleaned up, and each HTTP call is one coloured line.
Quick start #
1. Install
flutter pub add dev:tidy_log
Use flutter pub add tidy_log (not dev:) if your app code will call TidyLog or TidyDioInterceptor.
2. Run
| You run the app from | Set up once | Then run |
|---|---|---|
| A terminal | nothing | dart run tidy_log run -d <device> (any flutter run flags) |
| VS Code | dart run tidy_log:setup |
Run and Debug → pick a "(tidy logs)" config → F5 |
| Android Studio / IntelliJ | dart run tidy_log:setup --sdk |
Settings → Languages & Frameworks → Flutter → SDK path = the folder it prints, then Run as usual |
The tests run in CI on Linux, macOS and Windows. On Windows, the Android Studio shim is new in 0.2.1 (see Limits). The native cleanup is for Android; on iOS the in-app logger still works.
3. HTTP calls (Dio)
| Who logs the HTTP call | What to add | Where "200, but it failed" rules go |
|---|---|---|
Your own Dio client |
dio.interceptors.add(TidyDioInterceptor()) |
TidyDioInterceptor(rules: [...]) in Dart |
A package that prints pretty_dio_logger boxes (╔╣ Request ║ GET) |
nothing: the runner folds each call into one line | http_rules: in tidy_log.yaml in the app root |
Rules for common response bodies:
| Your API answers | Rule in Dart | Rule in tidy_log.yaml (under http_rules:) |
|---|---|---|
{"success": false, "message": "…"} |
ResponseRule.field('success', {true: HttpOutcome.success, false: HttpOutcome.error}, message: 'message') |
- {field: success, values: {true: success, false: error}, message: message} |
{"type": 3, "messages": ["…"]}, where only type: 1 is a success |
ResponseRule.field('type', {1: HttpOutcome.success}, otherwise: HttpOutcome.error, message: 'messages') |
- {field: type, values: {1: success}, otherwise: error, message: messages} |
{"status": "WARNING", "message": "…"} |
ResponseRule.field('status', {'OK': HttpOutcome.success, 'WARNING': HttpOutcome.warning}, otherwise: HttpOutcome.error, message: 'message') |
- {field: status, values: {OK: success, WARNING: warning}, otherwise: error, message: message} |
Status colours: green 2xx, light yellow 3xx, yellow 4xx, magenta 5xx, and red when a rule says a call failed (200 ✕, with the reason on the next line).
That's all you need. Everything below is detail.
What it does #
- Errors open with where they happened (
at lib/app/view/home_page.dart:145:12 HomePage._onTap, the location in blue so it stands out), followed by a short dimmed trail of your own frames and a count of hidden frames. - Native logcat lines lose their
D/WindowOnBackDispatcher(31800):prefix. The tag moves to a dim suffix in a fixed column, and the level becomes a colouredDBG / INF / WRN / ERRlabel. In a terminal, lines are fitted to the window instead of wrapping. - Noise is handled for you:
- Identical lines collapse into one line with
×30. - Near-duplicates fold into
↳ +6 similar. - Native Java stack traces fold to the exception, the first non-SDK frame and the
caused byline. - Chatty Android tags are hidden by default.
- Identical lines collapse into one line with
- Each Dio call gets one aligned line (method, path, status, duration, time, host in fixed columns), coloured by status, with its body and response underneath one field per line. Secrets are masked (see below). Response rules can flag a 200 whose body says it failed (
200 ✕, with the reason on the next line). - Packages that log HTTP with pretty_dio_logger-style boxes (
╔╣ Request ║ GET) need no change: the runner pairs each request with its response and prints the same one line, without the header and timeout rows. Anything shaped like a JWT is masked wherever it appears, even when a logger prints it without its key. - Secrets are masked. In the app,
TidyLogandTidyDioInterceptormask what they print. The runner also masks native lines, the Flutter tool's stderr, and lines that other loggers print in their own colours, in the console and in the clean copy.- Keys masked by default (
redact_keys/redactKeyschange the list):pin,password,passcode,otp,token,secret,cvv,authorization,pincode,otpcode,cvv2,cvc,apikey,cookie,setcookie,sessionid,privatekey,accesskey. Case,_and-are ignored, and a key matches when it ends with one of these (softToken,walletPin,X-Api-Key), sopinCountandtokenExpiryare left alone. - The whole value is masked: a quoted value up to its closing quote, an unquoted one to the end of the field, a list as a whole, and in a body everything nested under a sensitive key. An
Authorizationvalue is masked whole, whether it isBearer,Basic,TokenorDigest. - URL query values are masked before the URL is percent-decoded. Keys are also found in escaped JSON (
\"password\") and in form keys (user[password]).
- Keys masked by default (
- Each new app process gets a divider, and so does each hot restart.
- Every run also writes a clean copy to
.dart_tool/tidy_log/last_run.log, in plain text with no colours and no tags, ready to paste.
──────── app started · pid 31800 ────────
ERR EncryptedSharedPreferences initialization failed. Falling back… · FlutterSecureStorage
SecurityException: Could not decrypt key. decryption failed
at com.it_nomads.fluttersecurestorage.crypto.EncryptedSharedPreferences.decryptKey(…:561)
┊ … 6 frames hidden · caused by GeneralSecurityException: decryption failed
DBG Sending viewport metrics to the engine. · FlutterJNI ×30
NAV /login → /loginSelectAccountPage
POST /api/Auth/OpenSession 200 1,010 ms 15:22:58 10.0.2.2:4013
resp type: 2
messages: [unvalid api sign .....en-US]
ERR Error refreshing session: unvalid api sign .....en-US
at package:core_kit/infrastructure/network/httpHandler/handle_exception.dart:42:5 HandleException.handleException
┊ package:core_kit/…/network_service_impl.dart:97:14 NetworkServiceImpl.requestService
Before and after: the same demo session is 104 lines with flutter run and 24 with tidy_log. Both logs are in full on the example page (the Example tab on pub.dev).
Setup in detail #
- In a terminal,
dart run tidy_log runaccepts everyflutter runflag, andr,Randqact without Enter, as influtter run. - Pub workspaces (Melos) work too: the launchers and the shim also look for
.dart_tool/package_config.jsonin parent folders. - The native part needs nothing else. The in-app logger is optional.
What dart run tidy_log:setup does (VS Code) #
- It writes
.vscode/tidy_flutterand.vscode/tidy_flutter.bat. These are small launchers that startdart run tidy_logwith the first Flutter SDK they find:FLUTTER_ROOT(VS Code sets it to the SDK the Dart extension uses), then.fvm/flutter_sdknext to.vscode(fvm), thenflutteronPATH. Untilflutter pub gethas run, they fall back to plain flutter, so a fresh clone always launches. - It adds a
<name> (tidy logs)copy of every Dart config in.vscode/launch.json, except test configs, or creates the file. The copies go first in the list, so a new checkout starts with a tidy launch selected (VS Code remembers the config you last picked, so pick one once if you used another before). Setup only inserts text at the top of the list, so your own configs and comments stay as they are. Running it again in a project set up by 0.2.1 or earlier moves the existing copies to the top. - It prints an optional
main.dartsnippet that uses your app's package name.
Commit the three files so your team gets them. --dry-run shows the changes first, and --remove takes out only what setup added.
What dart run tidy_log:setup --sdk does (Android Studio / IntelliJ) #
The JetBrains Flutter plugin runs <Flutter SDK path>/bin/flutter run --machine itself, and has no option to run another program. So setup creates a shim SDK at ~/.tidy_log/flutter_sdk:
- It's a few KB of symlinks. They point to your real SDK, which is never modified, so
flutter upgradekeeps working. On Windows, plain files are copied rather than linked. - Only
bin/flutteris different. It's a small script:flutter runandflutter attach, in projects that depend on tidy_log, go through tidy_log.- Every other command, and every other project, goes straight to your real Flutter.
To keep typing plain flutter run in a terminal too, put the shim's bin first in your PATH (setup prints the line). The shim is a snapshot of the SDK's file list, so rerun dart run tidy_log:setup --sdk after moving your SDK, after a flutter upgrade that adds files, and after switching versions with a version manager (fvm, Homebrew) that changes the SDK path. --sdk --remove deletes the shim, and you can always point the IDE back at your real SDK.
How it works #
The native X/Tag(pid): lines come from the Flutter tool, which forwards logcat. App code can't change them, so tidy_log sits between your IDE and flutter:
- It runs the real
flutterand passes the IDE's JSON protocol through untouched, so breakpoints, hot reload and DevTools keep working. - It restyles only the device log lines.
The runner finds the real flutter from TIDY_FLUTTER_BIN, then FLUTTER_ROOT, then PATH. If that is the shim, it uses the real SDK the shim points to.
In-app logger (optional) #
To call TidyLog from your code, add tidy_log as a regular dependency (flutter pub add tidy_log) rather than a dev one.
import 'package:tidy_log/tidy_log.dart';
void main() {
TidyLog.configure(
projectPackages: ['app', 'core_kit'], // your own packages; the first is the app, so its paths print as lib/…
minLevel: Level.debug, // the lowest level that is printed
httpBodies: HttpBodies.always, // body/resp lines: always (default), onFailure or never
httpRules: [/* … */], // how to read "200, but it failed" bodies (see Response rules)
redactKeys: ['pin', 'password', 'token'], // keys whose values are masked (these and a few more by default)
);
TidyLog.installErrorHooks(); // tidy Flutter errors and uncaught async errors; call it before Sentry
runApp(const App());
}
TidyLog.i('Signed in', tag: 'Auth');
TidyLog.e('Transfer failed', tag: 'Transfer', error: e, stackTrace: s);
final dio = Dio()..interceptors.add(TidyDioInterceptor()); // one line per HTTP call, instead of a pretty logger
dart run tidy_log:setup prints this snippet with your app's package name filled in.
installErrorHooks() replaces Flutter's ══╡ EXCEPTION CAUGHT ╞══ box, and logs uncaught async errors. Every error gets its own location line, including the ones Flutter would print only as Another exception was thrown: …. Errors that are just side effects of the one before (the dozen RenderBox was not laid out after an unbounded-height error) are folded into one ┊ +12 follow-on errors hidden line.
Order matters: call it before Sentry's init. Crash reporters keep the FlutterError.onError handler they find and call it after capturing an error. If the reporter is set up first, it keeps Flutter's box printer instead. The hooks then leave the reporter alone and print a one-line hint.
The hooks print errors themselves rather than through FlutterError.presentError, because in debug runs the widget inspector replaces presentError once the binding starts. To keep the IDE's structured errors instead, use installErrorHooks(keepStructuredErrors: true). Flutter errors then go through Flutter's presenter, which the widget inspector takes over in debug runs, so they are not tidied: no location-first line and no folding of follow-on errors. Uncaught async errors are still tidied.
Some errors get a short description instead of their toString():
| Error | Printed as |
|---|---|
DioException |
DioException · receive timeout (1 s), · bad response 500, · connection refused, · host lookup failed: api.x |
PlatformException |
PlatformException(UNAVAILABLE): Card reader is not connected., then native at <first app frame> and a caused by note when it carries a Java stack |
FlutterError (uncaught) |
the summary and the first two hint lines |
Add your own with TidyLog.configure(errorText: (e) => e is ApiFailure ? 'ApiFailure ${e.code}' : null).
HTTP calls #
The status is green for 2xx, light yellow for 3xx, yellow for 4xx and magenta for 5xx. An error a response rule finds on a lower status (for example type: 2 on a 200) is red, so a server failure and a rejected request look different. A call that never got a response shows ERR and a short reason. Each call is logged at the level of its outcome, so TidyLog.configure(minLevel: Level.warning) hides the successful ones.
body and resp lines are printed for every call by default. Choose for yourself:
TidyLog.configure(httpBodies: HttpBodies.onFailure); // or always (default), never
dio.interceptors.add(TidyDioInterceptor(bodies: HttpBodies.never)); // per client, wins over configure
Response rules: "200, but it failed" #
Some backends answer 200 to everything and put the real result in the body. Tell tidy_log how to read it, and the line is coloured by what really happened:
TidyLog.configure(httpRules: [ // or TidyDioInterceptor(rules: [...]) for one client
// {"success": false, "message": "Insufficient balance"}
ResponseRule.field('success', {true: HttpOutcome.success, false: HttpOutcome.error}, message: 'message'),
// {"response_type": "WARNING", "messages": ["Session expires in 2 minutes"]}
ResponseRule.field('response_type', {
'SUCCESS': HttpOutcome.success,
'WARNING': HttpOutcome.warning,
'ERROR': HttpOutcome.error,
}, message: 'messages'),
// {"type": 2, ...} only on the auth service
ResponseRule.field('type', {2: HttpOutcome.error}, message: 'messages',
when: (request) => request.path.startsWith('/api/Auth')),
// anything else
ResponseRule.custom((response) => (response.data as Map?)?['errors'] != null
? const RuleVerdict(HttpOutcome.error, message: 'has errors')
: null),
]);
POST /api/wallet/pay 200 ✕ 12 ms 21:48:42 127.0.0.1:45887
✕ Insufficient balance
rule success = false → error
GET /api/session 200 ! 4 ms 21:48:42 127.0.0.1:45887
! Session expires in 2 minutes
rule response_type = "WARNING" → warning
POST /api/Auth/OpenSession 200 ✕ 1,010 ms 15:22:58 10.0.2.2:4013
✕ unvalid api sign
rule type = 2 → error
- The path is dotted (
meta.errors.0.code). Bodies that arrive as JSON text are decoded. - Values match leniently:
2matches'2', and strings match whatever their case. message:points at a string, or at a list whose first item is used.- A value missing from the map gets
otherwise:, or no verdict at all (the status colour stays). - Rules also run on error responses, so a 400 can be just a warning. The first rule with a verdict wins.
- Rules only change the log line (colour, level, message). They never change what Dio does. A rule that throws is reported once per rule as a
WRN, and the call is still logged.
Configuration: tidy_log.yaml in the app root #
Every key is optional.
preset: quiet # quiet (default) hides Android UI chatter; all shows everything restyled
project_packages: [app, core_kit] # the app's own name from pubspec.yaml is added first automatically
hide_tags: [FlutterGeolocator]
show_tags: [ImeTracker] # wins over the preset and hide_tags
hide_messages: ['^Width is zero']
min_native_level: debug # verbose | debug | info | warning | error
redact_keys: [pin, password, passcode, otp, token, secret, cvv, authorization, pincode, otpcode, cvv2, cvc, apikey, cookie, setcookie, sessionid, privatekey, accesskey] # the defaults; your list replaces them
max_width: 160 # widest console line when the output is not a terminal (a terminal's own width is used); never applies to the clean copy
color: true # or set NO_COLOR=1
rules: # label your own Dart print lines
- match: '^unhandled element'
label: SVG
tone: warning # plain dim secondary error warning accent success
http_rules: # judge pretty_dio_logger boxes by their body, like ResponseRule.field in the app
- field: type # body path; dotted for nested fields (meta.status, errors.0.code)
values: {1: success} # success | info | warning | error
otherwise: error # any other value present; leave it out to keep the status colour
message: messages # text shown as the reason (a string, or a list's first item)
http_rules are for HTTP calls another package logs with a pretty_dio_logger style interceptor, which the runner folds into one line; the first rule with a verdict wins. A mistyped outcome stops the run with a message naming the rule, so a typo never turns a rule off quietly. For your own Dio clients, TidyDioInterceptor(rules: …) does the same in the app.
The quiet preset hides these tags: WindowOnBackDispatcher, InsetsController, ImeTracker, InputConnectionAdaptor, Surface, HWUI, nativeloader, cr_*, CompatChangeReporter, Badge, NexusLauncherBadge, ApplicationLoaders, ResourcesManager, VRI[*, ViewRootImpl, WindowExtensionsImpl, WindowLayoutComponentImpl, UiContextUtils, AudioSystem, libc, DefaultDispatch, InteractionJankMonitor, FlutterActivityAndFragmentDelegate, ProfileInstaller and DesktopExperienceFlags. It also hides avc: denied/granted lines and these start-up messages: Beginning load of flutter, flutter (null) was loaded normally!, Width is zero and ART's … GC freed …. Skipped N frames! stays, because it is a real performance signal.
Other uses #
dart run tidy_log run -d emulator-5554 # flutter run in a terminal, tidied
adb logcat | dart run tidy_log rewrite # any logcat stream
dart run tidy_log rewrite --plain < saved.log > clean.log # clean a saved log
If you can't use the runner, the package still works on its own. To hide native noise in VS Code, type this into the Debug Console's filter box:
!FlutterJNI, !WindowOnBackDispatcher, !InsetsController, !ImeTracker
Limits #
- Android only for the native part. iOS has no logcat prefixes, but the package still works there.
- The error hooks act only in debug builds. In profile and release builds, and after
TidyLog.configure(enabled: false),installErrorHooks()does nothing and Flutter's own error handling stays. - VS Code reads
.vscode/launch.jsononly at the workspace root, and setup writes.vscodenext topubspec.yaml. Open the app's own folder in VS Code and run setup there. If the app is in a subfolder of the folder you opened, VS Code does not see its "(tidy logs)" configs. - On Windows,
setup --sdklinks the SDK's folders as directory junctions, so it needs neither Developer Mode nor an administrator shell. The shim on Windows is new in 0.2.1 and has had less use than on macOS and Linux. - The shim takes the first argument that is not a flag as the command, so a flag with a value placed before the command (
flutter -d emu run) is not recognised, and that run gets plain output. IDEs pass the device afterrun. - Repeat counts and open blocks are held back until the next different line, or until the output has been quiet for 200 ms.
- Dart-Code links paths in the console.
lib/…paths open from the workspace root, andpackage:paths are resolved by the debug adapter.
Development #
flutter test # the package: parser, folding, redaction, golden session, logger, hooks, setup, shim
cd example && flutter test # demo screen
test/core/fixtures/sample_session.txt is a real F5 session excerpt, with PINs and user IDs replaced. Its expected output is reviewed by hand. See test/core/golden_session_test.dart for how to regenerate it after an intended change.
sample_app/ is a scenario bench that compares tidy_log with the default output (see its README).