Skip to content

Commit 3c0dee9

Browse files
gnpricechrisbobbe
authored andcommitted
log: Do some logging only in debug app, not in tests
1 parent b2a62f0 commit 3c0dee9

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

lib/api/core.dart

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import 'dart:convert';
22

3-
import 'package:flutter/foundation.dart';
43
import 'package:http/http.dart' as http;
54

5+
import '../log.dart';
6+
67
class Auth {
78
Auth({required this.realmUrl, required this.email, required this.apiKey})
89
: assert(realmUrl.query.isEmpty && realmUrl.fragment.isEmpty);
@@ -74,7 +75,7 @@ class LiveApiConnection extends ApiConnection {
7475
assert(_isOpen);
7576
final url = auth.realmUrl.replace(
7677
path: "/api/v1/$route", queryParameters: encodeParameters(params));
77-
if (kDebugMode) print("GET $url");
78+
assert(debugLog("GET $url"));
7879
final response = await _client.get(url, headers: _headers());
7980
if (response.statusCode != 200) {
8081
throw Exception("error on GET $route: status ${response.statusCode}");

lib/log.dart

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
2+
/// Whether [debugLog] should do anything.
3+
///
4+
/// This has an effect only in a debug build.
5+
bool debugLogEnabled = false;
6+
7+
/// Print a log message, if debug logging is enabled.
8+
///
9+
/// In a debug build, if [debugLogEnabled] is true, this prints the given
10+
/// message to the log. Otherwise it does nothing.
11+
///
12+
/// Typically we set [debugLogEnabled] so that this will print when running
13+
/// the app in a debug build, but not when running tests.
14+
///
15+
/// Call sites of this function should be enclosed in `assert` expressions, so
16+
/// that any interpolation to construct the message happens only in debug mode.
17+
/// To help make that convenient, this function always returns true.
18+
///
19+
/// Example usage:
20+
/// ```dart
21+
/// assert(debugLog("Got frobnitz: $frobnitz"));
22+
/// ```
23+
bool debugLog(String message) {
24+
assert(() {
25+
// TODO(log): make it convenient to enable these logs in tests for debugging a failing test
26+
if (debugLogEnabled) {
27+
print(message); // ignore: avoid_print
28+
}
29+
return true;
30+
}());
31+
return true;
32+
}

lib/main.dart

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import 'package:flutter/material.dart';
22

3+
import 'log.dart';
34
import 'widgets/app.dart';
45

56
void main() {
7+
assert(() {
8+
debugLogEnabled = true;
9+
return true;
10+
}());
611
runApp(const ZulipApp());
712
}

0 commit comments

Comments
 (0)