Skip to content

Updated logs #230

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 25, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions webdev/lib/src/command/daemon_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,21 @@ class DaemonCommand extends Command<int> {
Future<int> run() async {
var daemon = Daemon(_stdinCommandStream, _stdoutCommandResponse);
var daemonDomain = DaemonDomain(daemon);
// Override the default logHandler.
logHandler = (level, message) {
daemonDomain.sendEvent(
'daemon.logMessage', {'level': '$level', 'message': message});
};
daemon.registerDomain(daemonDomain);
var configuration = Configuration(launchInChrome: true, debug: true);
var pubspecLock = await readPubspecLock(configuration);
var buildOptions = buildRunnerArgs(pubspecLock, configuration);
var port = await findUnusedPort();
var workflow = await DevWorkflow.start(
configuration, buildOptions, {'web': port}, (level, message) {
daemonDomain.sendEvent(
'daemon.logMessage', {'level': '$level', 'message': message});
});
configuration,
buildOptions,
{'web': port},
);
daemon.registerDomain(AppDomain(daemon, workflow.serverManager));
await daemon.onExit;
await workflow.shutDown();
Expand Down
6 changes: 4 additions & 2 deletions webdev/lib/src/command/serve_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,8 @@ class ServeCommand extends Command<int> {
Future<int> run() async {
Configuration configuration;
configuration = Configuration.fromArgs(argResults);
// Globally trigger verbose logs.
verboseLogs = configuration.verbose;
var pubspecLock = await readPubspecLock(configuration);
// Forward remaining arguments as Build Options to the Daemon.
// This isn't documented. Should it be advertised?
Expand All @@ -101,8 +103,8 @@ class ServeCommand extends Command<int> {
.where((arg) => arg.contains(':') || !arg.startsWith('--'))
.toList();
var targetPorts = _parseDirectoryArgs(directoryArgs);
var workflow = await DevWorkflow.start(
configuration, buildOptions, targetPorts, colorLog);
var workflow =
await DevWorkflow.start(configuration, buildOptions, targetPorts);
await workflow.done;
return 0;
}
Expand Down
38 changes: 38 additions & 0 deletions webdev/lib/src/daemon/app_domain.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:build_daemon/data/build_status.dart';
import 'package:dwds/service.dart';
import 'package:vm_service_lib/vm_service_lib.dart';

Expand All @@ -22,7 +23,9 @@ class AppDomain extends Domain {
AppDebugServices _appDebugServices;
DebugService get _debugService => _appDebugServices?.debugService;
VmService get _vmService => _appDebugServices?.webdevClient?.client;
StreamSubscription<BuildResult> _resultSub;
bool _isShutdown = false;
int _buildProgressEventId;
var _progressEventId = 0;

void _initialize(ServerManager serverManager) async {
Expand Down Expand Up @@ -53,6 +56,35 @@ class AppDomain extends Domain {
'port': _debugService.port,
'wsUri': _debugService.wsUri,
});
_resultSub = devHandler.buildResults.listen((result) {
switch (result.status) {
case BuildStatus.started:
_buildProgressEventId = _progressEventId++;
sendEvent('app.progress', {
'appId': _appId,
'id': '$_buildProgressEventId',
'message': 'Starting Build',
'progressId': 'build.started',
});
break;
case BuildStatus.failed:
sendEvent('app.progress', {
'appId': _appId,
'id': '$_buildProgressEventId',
'message': 'Build Failed',
'progressId': 'build.failed',
});
break;
case BuildStatus.succeeded:
sendEvent('app.progress', {
'appId': _appId,
'id': '$_buildProgressEventId',
'message': 'Build Succeeded',
'progressId': 'build.succeeded',
});
break;
}
});

// Shutdown could have been triggered while awaiting above.
if (_isShutdown) dispose();
Expand Down Expand Up @@ -89,6 +121,7 @@ class AppDomain extends Domain {
}
// TODO(grouma) - Support pauseAfterRestart.
// var pauseAfterRestart = getBoolArg(args, 'pause') ?? false;
var stopwatch = Stopwatch()..start();
_progressEventId++;
sendEvent('app.progress', {
'appId': _appId,
Expand All @@ -103,6 +136,10 @@ class AppDomain extends Domain {
'finished': true,
'progressId': 'hot.restart',
});
sendEvent('daemon.logMessage', {
'level': 'info',
'message': 'Restared application in ${stopwatch.elapsedMilliseconds}ms'
});
return {
'code': response.type == 'Success' ? 0 : 1,
'message': response.toString()
Expand All @@ -120,6 +157,7 @@ class AppDomain extends Domain {
@override
void dispose() {
_isShutdown = true;
_resultSub.cancel();
_appDebugServices.close();
}
}
13 changes: 4 additions & 9 deletions webdev/lib/src/serve/dev_workflow.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import '../serve/webdev_server.dart';
Future<BuildDaemonClient> _startBuildDaemon(
String workingDirectory,
List<String> buildOptions,
void Function(Level level, String message) logHandler,
) async {
logHandler(Level.INFO, 'Connecting to the build daemon...');
try {
Expand Down Expand Up @@ -68,7 +67,6 @@ Future<ServerManager> _startServerManager(
String workingDirectory,
BuildDaemonClient client,
DevTools devTools,
void Function(Level level, String message) logHandler,
) async {
var assetPort = daemonPort(workingDirectory);
var serverOptions = Set<ServerOptions>();
Expand Down Expand Up @@ -96,7 +94,6 @@ Future<ServerManager> _startServerManager(

Future<DevTools> _startDevTools(
Configuration configuration,
void Function(Level level, String message) logHandler,
) async {
if (configuration.debug) {
var devTools = await DevTools.start(configuration.hostname);
Expand Down Expand Up @@ -132,14 +129,12 @@ class DevWorkflow {
Configuration configuration,
List<String> buildOptions,
Map<String, int> targetPorts,
void Function(Level level, String message) logHandler,
) async {
var workingDirectory = Directory.current.path;
var client =
await _startBuildDaemon(workingDirectory, buildOptions, logHandler);
var devTools = await _startDevTools(configuration, logHandler);
var serverManager = await _startServerManager(configuration, targetPorts,
workingDirectory, client, devTools, logHandler);
var client = await _startBuildDaemon(workingDirectory, buildOptions);
var devTools = await _startDevTools(configuration);
var serverManager = await _startServerManager(
configuration, targetPorts, workingDirectory, client, devTools);
var chrome = await _startChrome(configuration, serverManager, client);
logHandler(Level.INFO, 'Registering build targets...');
for (var target in targetPorts.keys) {
Expand Down
9 changes: 5 additions & 4 deletions webdev/lib/src/serve/handlers/dev_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ class DevHandler {
final String _hostname;
final _connectedApps = StreamController<ConnectRequest>.broadcast();
final _servicesByAppId = <String, Future<AppDebugServices>>{};
final Stream<BuildResult> buildResults;

Stream<ConnectRequest> get connectedApps => _connectedApps.stream;

DevHandler(Stream<BuildResult> buildResults, this._devTools,
this._assetHandler, this._hostname) {
DevHandler(
this.buildResults, this._devTools, this._assetHandler, this._hostname) {
_sub = buildResults.listen(_emitBuildResults);
_listen();
}
Expand Down Expand Up @@ -166,7 +167,7 @@ class DevHandler {
var chrome = await Chrome.connectedInstance;
var debugService =
await startDebugService(chrome.chromeConnection, instanceId);
colorLog(
logHandler(
Level.INFO,
'Debug service listening on '
'ws://${debugService.hostname}:${debugService.port}\n');
Expand All @@ -178,7 +179,7 @@ class DevHandler {
debugService.chromeProxyService.tabConnection.onClose.first.then((_) {
appServices.close();
_servicesByAppId.remove(appId);
colorLog(
logHandler(
Level.INFO,
'Stopped debug service on '
'ws://${debugService.hostname}:${debugService.port}\n');
Expand Down
11 changes: 7 additions & 4 deletions webdev/lib/src/serve/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ Future<int> findUnusedPort() async {
return port;
}

var verboseLogs = false;

/// Colors the message and writes it to stdout.
///
/// If the [level] is not contained in the message, one will be inserted.
void colorLog(Level level, String message, {bool verbose}) {
verbose ??= false;
void colorLog(Level level, String message) {
AnsiCode color;
if (level < Level.WARNING) {
color = cyan;
Expand All @@ -41,17 +42,19 @@ void colorLog(Level level, String message, {bool verbose}) {
color = red;
}
var multiline = message.contains('\n') && !message.endsWith('\n');
var eraseLine = verbose ? '' : '\x1b[2K\r';
var eraseLine = verboseLogs ? '' : '\x1b[2K\r';
var colorLevel = color.wrap('[$level]');

stdout.write('$eraseLine$colorLevel $message');

// Prevent multilines and severe messages from being erased.
if (level > Level.INFO || verbose || multiline) {
if (level > Level.INFO || verboseLogs || multiline) {
stdout.writeln('');
}
}

void Function(Level level, String message) logHandler = colorLog;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't very discoverable - especially buried at the end of the serve/utils file :D.

If we are going with a global like this I would move it to a lib/src/logging.dart file so that its a bit easier to find, and document it clearly.

I would also consider a Zone variable, which at least removes some of the limitations of general global variables.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved logging logic to logging.dart. Given that this logging logic is only used by the serve command I don't think we really need a zone. If it gets more complicated in the future, which I don't anticipate, we can revisit.


String trimLevel(Level level, String message) => message.startsWith('[$level]')
? message.replaceFirst('[$level]', '').trimLeft()
: message;
Expand Down