diff --git a/packages/flutter_tools/lib/src/ios/simulators.dart b/packages/flutter_tools/lib/src/ios/simulators.dart index 1cc51266e3..f28bde55af 100644 --- a/packages/flutter_tools/lib/src/ios/simulators.dart +++ b/packages/flutter_tools/lib/src/ios/simulators.dart @@ -580,20 +580,41 @@ class IOSSimulator extends Device { } } -/// Launches the device log reader process on the host. -Future launchDeviceLogTool(IOSSimulator device) async { - // Versions of iOS prior to iOS 11 log to the simulator syslog file. - if (await device.sdkMajorVersion < 11) { - return processUtils.start(['tail', '-n', '0', '-F', device.logFilePath]); - } +/// Launches the device log reader process on the host and parses the syslog. +@visibleForTesting +Future launchDeviceSystemLogTool(IOSSimulator device) async { + return processUtils.start(['tail', '-n', '0', '-F', device.logFilePath]); +} + +/// Launches the device log reader process on the host and parses unified logging. +@visibleForTesting +Future launchDeviceUnifiedLogging (IOSSimulator device, String appName) async { + // Make NSPredicate concatenation easier to read. + String orP(List clauses) => '(${clauses.join(" OR ")})'; + String andP(List clauses) => clauses.join(' AND '); + String notP(String clause) => 'NOT($clause)'; + + final String predicate = andP([ + 'eventType = logEvent', + if (appName != null) 'processImagePath ENDSWITH "$appName"', + // Either from Flutter or Swift (maybe assertion or fatal error) or from the app itself. + orP([ + 'senderImagePath ENDSWITH "/Flutter"', + 'senderImagePath ENDSWITH "/libswiftCore.dylib"', + 'processImageUUID == senderImageUUID', + ]), + // Filter out some messages that clearly aren't related to Flutter. + notP('eventMessage CONTAINS ": could not find icon for representation -> com.apple."'), + notP('eventMessage BEGINSWITH "assertion failed: "'), + notP('eventMessage CONTAINS " libxpc.dylib "'), + ]); - // For iOS 11 and above, use /usr/bin/log to tail process logs. - // Run in interactive mode (via script), otherwise /usr/bin/log buffers in 4k chunks. (radar: 34420207) return processUtils.start([ - 'script', '/dev/null', '/usr/bin/log', 'stream', '--style', 'syslog', '--predicate', 'processImagePath CONTAINS "${device.id}"', + _xcrunPath, 'simctl', 'spawn', device.id, 'log', 'stream', '--style', 'json', '--predicate', predicate, ]); } +@visibleForTesting Future launchSystemLogTool(IOSSimulator device) async { // Versions of iOS prior to 11 tail the simulator syslog file. if (await device.sdkMajorVersion < 11) { @@ -630,11 +651,18 @@ class _IOSSimulatorLogReader extends DeviceLogReader { String get name => device.name; Future _start() async { - // Device log. - await device.ensureLogsExists(); - _deviceProcess = await launchDeviceLogTool(device); - _deviceProcess.stdout.transform(utf8.decoder).transform(const LineSplitter()).listen(_onDeviceLine); - _deviceProcess.stderr.transform(utf8.decoder).transform(const LineSplitter()).listen(_onDeviceLine); + // Unified logging iOS 11 and greater (introduced in iOS 10). + if (await device.sdkMajorVersion >= 11) { + _deviceProcess = await launchDeviceUnifiedLogging(device, _appName); + _deviceProcess.stdout.transform(utf8.decoder).transform(const LineSplitter()).listen(_onUnifiedLoggingLine); + _deviceProcess.stderr.transform(utf8.decoder).transform(const LineSplitter()).listen(_onUnifiedLoggingLine); + } else { + // Fall back to syslog parsing. + await device.ensureLogsExists(); + _deviceProcess = await launchDeviceSystemLogTool(device); + _deviceProcess.stdout.transform(utf8.decoder).transform(const LineSplitter()).listen(_onSysLogDeviceLine); + _deviceProcess.stderr.transform(utf8.decoder).transform(const LineSplitter()).listen(_onSysLogDeviceLine); + } // Track system.log crashes. // ReportCrash[37965]: Saved crash report for FlutterRunner[37941]... @@ -729,7 +757,7 @@ class _IOSSimulatorLogReader extends DeviceLogReader { String _lastLine; - void _onDeviceLine(String line) { + void _onSysLogDeviceLine(String line) { globals.printTrace('[DEVICE LOG] $line'); final Match multi = _lastMessageMultipleRegex.matchAsPrefix(line); @@ -752,6 +780,19 @@ class _IOSSimulatorLogReader extends DeviceLogReader { } } + // "eventMessage" : "flutter: 21", + static final RegExp _unifiedLoggingEventMessageRegex = RegExp(r'.*"eventMessage" : (".*")'); + void _onUnifiedLoggingLine(String line) { + // The log command predicate handles filtering, so every log eventMessage should be decoded and added. + final Match eventMessageMatch = _unifiedLoggingEventMessageRegex.firstMatch(line); + if (eventMessageMatch != null) { + final dynamic decodedJson = jsonDecode(eventMessageMatch.group(1)); + if (decodedJson is String) { + _linesController.add(decodedJson); + } + } + } + String _filterSystemLog(String string) { final Match match = _mapRegex.matchAsPrefix(string); return match == null ? string : '${match.group(1)}: ${match.group(2)}'; diff --git a/packages/flutter_tools/test/general.shard/ios/simulators_test.dart b/packages/flutter_tools/test/general.shard/ios/simulators_test.dart index d5934319ea..79cdf772a0 100644 --- a/packages/flutter_tools/test/general.shard/ios/simulators_test.dart +++ b/packages/flutter_tools/test/general.shard/ios/simulators_test.dart @@ -410,7 +410,7 @@ void main() { ); }); - group('launchDeviceLogTool', () { + group('device log tool', () { MockProcessManager mockProcessManager; MockXcode mockXcode; MockSimControl mockSimControl; @@ -423,7 +423,7 @@ void main() { mockXcode = MockXcode(); }); - testUsingContext('uses tail on iOS versions prior to iOS 11', () async { + testUsingContext('syslog uses tail', () async { final IOSSimulator device = IOSSimulator( 'x', name: 'iPhone SE', @@ -431,7 +431,7 @@ void main() { simControl: mockSimControl, xcode: mockXcode, ); - await launchDeviceLogTool(device); + await launchDeviceSystemLogTool(device); expect( verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single, contains('tail'), @@ -442,7 +442,7 @@ void main() { FileSystem: () => fileSystem, }); - testUsingContext('uses /usr/bin/log on iOS 11 and above', () async { + testUsingContext('unified logging with app name', () async { final IOSSimulator device = IOSSimulator( 'x', name: 'iPhone SE', @@ -450,52 +450,35 @@ void main() { simControl: mockSimControl, xcode: mockXcode, ); - await launchDeviceLogTool(device); - expect( - verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single, - contains('/usr/bin/log'), - ); - }, - overrides: { - ProcessManager: () => mockProcessManager, - FileSystem: () => fileSystem, - }); - }); + await launchDeviceUnifiedLogging(device, 'Runner'); - group('launchSystemLogTool', () { - MockProcessManager mockProcessManager; + const String expectedPredicate = 'eventType = logEvent AND ' + 'processImagePath ENDSWITH "Runner" AND ' + '(senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" OR processImageUUID == senderImageUUID) AND ' + 'NOT(eventMessage CONTAINS ": could not find icon for representation -> com.apple.") AND ' + 'NOT(eventMessage BEGINSWITH "assertion failed: ") AND ' + 'NOT(eventMessage CONTAINS " libxpc.dylib ")'; - MockSimControl mockSimControl; - MockXcode mockXcode; - - setUp(() { - mockSimControl = MockSimControl(); - mockXcode = MockXcode(); - mockProcessManager = MockProcessManager(); - when(mockProcessManager.start(any, environment: null, workingDirectory: null)) - .thenAnswer((Invocation invocation) => Future.value(MockProcess())); - }); - - testUsingContext('uses tail on iOS versions prior to iOS 11', () async { - final IOSSimulator device = IOSSimulator( + final List command = verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single as List; + expect(command, [ + '/usr/bin/xcrun', + 'simctl', + 'spawn', 'x', - name: 'iPhone SE', - simulatorCategory: 'iOS 9.3', - simControl: mockSimControl, - xcode: mockXcode, - ); - await launchSystemLogTool(device); - expect( - verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single, - contains('tail'), - ); + 'log', + 'stream', + '--style', + 'json', + '--predicate', + expectedPredicate + ]); }, - overrides: { + overrides: { ProcessManager: () => mockProcessManager, FileSystem: () => fileSystem, }); - testUsingContext('uses /usr/bin/log on iOS 11 and above', () async { + testUsingContext('unified logging without app name', () async { final IOSSimulator device = IOSSimulator( 'x', name: 'iPhone SE', @@ -503,13 +486,32 @@ void main() { simControl: mockSimControl, xcode: mockXcode, ); - await launchSystemLogTool(device); - verifyNever(mockProcessManager.start(any, environment: null, workingDirectory: null)); + await launchDeviceUnifiedLogging(device, null); + + const String expectedPredicate = 'eventType = logEvent AND ' + '(senderImagePath ENDSWITH "/Flutter" OR senderImagePath ENDSWITH "/libswiftCore.dylib" OR processImageUUID == senderImageUUID) AND ' + 'NOT(eventMessage CONTAINS ": could not find icon for representation -> com.apple.") AND ' + 'NOT(eventMessage BEGINSWITH "assertion failed: ") AND ' + 'NOT(eventMessage CONTAINS " libxpc.dylib ")'; + + final List command = verify(mockProcessManager.start(captureAny, environment: null, workingDirectory: null)).captured.single as List; + expect(command, [ + '/usr/bin/xcrun', + 'simctl', + 'spawn', + 'x', + 'log', + 'stream', + '--style', + 'json', + '--predicate', + expectedPredicate + ]); }, - overrides: { - ProcessManager: () => mockProcessManager, - FileSystem: () => fileSystem, - }); + overrides: { + ProcessManager: () => mockProcessManager, + FileSystem: () => fileSystem, + }); }); group('log reader', () { @@ -525,55 +527,62 @@ void main() { mockXcode = MockXcode(); }); - testUsingContext('simulator can output `)`', () async { - when(mockProcessManager.start(any, environment: null, workingDirectory: null)) - .thenAnswer((Invocation invocation) { + group('syslog', () { + setUp(() { + final File syslog = fileSystem.file('system.log')..createSync(); + osx.environment['IOS_SIMULATOR_LOG_FILE_PATH'] = syslog.path; + }); + + testUsingContext('simulator can output `)`', () async { + when(mockProcessManager.start(any, environment: null, workingDirectory: null)) + .thenAnswer((Invocation invocation) { final Process mockProcess = MockProcess(); when(mockProcess.stdout) .thenAnswer((Invocation invocation) { - return Stream>.fromIterable(>[''' + return Stream>.fromIterable(>[''' 2017-09-13 15:26:57.228948-0700 localhost Runner[37195]: (Flutter) Observatory listening on http://127.0.0.1:57701/ 2017-09-13 15:26:57.228948-0700 localhost Runner[37195]: (Flutter) )))))))))) 2017-09-13 15:26:57.228948-0700 localhost Runner[37195]: (Flutter) #0 Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)''' - .codeUnits]); - }); + .codeUnits]); + }); when(mockProcess.stderr) - .thenAnswer((Invocation invocation) => const Stream>.empty()); + .thenAnswer((Invocation invocation) => const Stream>.empty()); // Delay return of exitCode until after stdout stream data, since it terminates the logger. when(mockProcess.exitCode) - .thenAnswer((Invocation invocation) => Future.delayed(Duration.zero, () => 0)); + .thenAnswer((Invocation invocation) => Future.delayed(Duration.zero, () => 0)); return Future.value(mockProcess); }); - final IOSSimulator device = IOSSimulator( - '123456', - simulatorCategory: 'iOS 11.0', - simControl: mockSimControl, - xcode: mockXcode, - ); - final DeviceLogReader logReader = device.getLogReader( - app: await BuildableIOSApp.fromProject(mockIosProject), - ); + final IOSSimulator device = IOSSimulator( + '123456', + simulatorCategory: 'iOS 10.3', + simControl: mockSimControl, + xcode: mockXcode, + ); + final DeviceLogReader logReader = device.getLogReader( + app: await BuildableIOSApp.fromProject(mockIosProject), + ); - final List lines = await logReader.logLines.toList(); - expect(lines, [ - 'Observatory listening on http://127.0.0.1:57701/', - '))))))))))', - '#0 Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)', - ]); - }, overrides: { - ProcessManager: () => mockProcessManager, - FileSystem: () => fileSystem, - }); + final List lines = await logReader.logLines.toList(); + expect(lines, [ + 'Observatory listening on http://127.0.0.1:57701/', + '))))))))))', + '#0 Object.noSuchMethod (dart:core-patch/dart:core/object_patch.dart:46)', + ]); + }, overrides: { + ProcessManager: () => mockProcessManager, + FileSystem: () => fileSystem, + Platform: () => osx, + }); - testUsingContext('log reader handles multiline messages', () async { - when(mockProcessManager.start(any, environment: null, workingDirectory: null)) - .thenAnswer((Invocation invocation) { + testUsingContext('log reader handles multiline messages', () async { + when(mockProcessManager.start(any, environment: null, workingDirectory: null)) + .thenAnswer((Invocation invocation) { final Process mockProcess = MockProcess(); when(mockProcess.stdout) .thenAnswer((Invocation invocation) { - // Messages from 2017 should pass through, 2020 message should not - return Stream>.fromIterable(>[''' + // Messages from 2017 should pass through, 2020 message should not + return Stream>.fromIterable(>[''' 2017-09-13 15:26:57.228948-0700 localhost Runner[37195]: (Flutter) Single line message 2017-09-13 15:26:57.228948-0700 localhost Runner[37195]: (Flutter) Multi line message continues... @@ -588,40 +597,94 @@ void main() { and goes... 2017-09-13 15:36:57.228948-0700 localhost Runner[37195]: (Flutter) Single line message, not the part of the above ''' - .codeUnits]); - }); + .codeUnits]); + }); when(mockProcess.stderr) - .thenAnswer((Invocation invocation) => const Stream>.empty()); + .thenAnswer((Invocation invocation) => const Stream>.empty()); // Delay return of exitCode until after stdout stream data, since it terminates the logger. when(mockProcess.exitCode) - .thenAnswer((Invocation invocation) => Future.delayed(Duration.zero, () => 0)); + .thenAnswer((Invocation invocation) => Future.delayed(Duration.zero, () => 0)); return Future.value(mockProcess); }); - final IOSSimulator device = IOSSimulator( - '123456', - simulatorCategory: 'iOS 11.0', - simControl: mockSimControl, - xcode: mockXcode, - ); - final DeviceLogReader logReader = device.getLogReader( - app: await BuildableIOSApp.fromProject(mockIosProject), - ); + final IOSSimulator device = IOSSimulator( + '123456', + simulatorCategory: 'iOS 10.3', + simControl: mockSimControl, + xcode: mockXcode, + ); + final DeviceLogReader logReader = device.getLogReader( + app: await BuildableIOSApp.fromProject(mockIosProject), + ); - final List lines = await logReader.logLines.toList(); - expect(lines, [ - 'Single line message', - 'Multi line message', - ' continues...', - ' continues...', - 'Multi line message again', - ' and it goes...', - ' and goes...', - 'Single line message, not the part of the above' - ]); - }, overrides: { - ProcessManager: () => mockProcessManager, - FileSystem: () => fileSystem, + final List lines = await logReader.logLines.toList(); + expect(lines, [ + 'Single line message', + 'Multi line message', + ' continues...', + ' continues...', + 'Multi line message again', + ' and it goes...', + ' and goes...', + 'Single line message, not the part of the above' + ]); + }, overrides: { + ProcessManager: () => mockProcessManager, + FileSystem: () => fileSystem, + Platform: () => osx, + }); + }); + + group('unified logging', () { + testUsingContext('log reader handles escaped multiline messages', () async { + when(mockProcessManager.start(any, environment: null, workingDirectory: null)) + .thenAnswer((Invocation invocation) { + final Process mockProcess = MockProcess(); + when(mockProcess.stdout) + .thenAnswer((Invocation invocation) { + return Stream>.fromIterable(>[''' +},{ + "traceID" : 37579774151491588, + "eventMessage" : "Single line message", + "eventType" : "logEvent" +},{ + "traceID" : 37579774151491588, + "eventMessage" : "Multi line message\\n continues...\\n continues..." +},{ + "traceID" : 37579774151491588, + "eventMessage" : "Single line message, not the part of the above", + "eventType" : "logEvent" +},{ +''' + .codeUnits]); + }); + when(mockProcess.stderr) + .thenAnswer((Invocation invocation) => const Stream>.empty()); + // Delay return of exitCode until after stdout stream data, since it terminates the logger. + when(mockProcess.exitCode) + .thenAnswer((Invocation invocation) => Future.delayed(Duration.zero, () => 0)); + return Future.value(mockProcess); + }); + + final IOSSimulator device = IOSSimulator( + '123456', + simulatorCategory: 'iOS 11.0', + simControl: mockSimControl, + xcode: mockXcode, + ); + final DeviceLogReader logReader = device.getLogReader( + app: await BuildableIOSApp.fromProject(mockIosProject), + ); + + final List lines = await logReader.logLines.toList(); + expect(lines, [ + 'Single line message', 'Multi line message\n continues...\n continues...', + 'Single line message, not the part of the above' + ]); + }, overrides: { + ProcessManager: () => mockProcessManager, + FileSystem: () => fileSystem, + }); }); });