Skip to content

Commit db4fdaa

Browse files
rigor789edusperoniNathanWalker
authored
feat(ios): structured app logs that follow relaunches (#6179)
* feat(ios): structured app logs that follow relaunches Devices stream com.apple.os_trace_relay and simulators use log stream, both selected by executable name, so logs survive closing and reopening the app. --log picks the scope: JS output by default, the app's native logs without debug entries with debug, everything with trace or all. Without a new enough ios-device-lib, devices fall back to the syslog relay. Debug builds ask the runtime for chunk markers through logChunkMarkers in the app's package.json, and the CLI stitches split messages back together per process and thread. * feat(ios): reassemble split app logs from the runtime's piece headers Asks the runtime for log format 1 through the logFormat key of the app's package.json, in place of logChunkMarkers. In format 1, each piece of a message the runtime had to split is logged as "[ns <id> <index>/<count>] <piece>", where the pieces are consecutive slices of the message. The stitcher now collects pieces by process and message id, prints the message as soon as its last piece arrives, and after 500 ms prints what it has with "<…lost…>" where pieces never arrived. A message can no longer be joined onto another one whose last piece os_log dropped. Pieces are joined before the entry is turned into text, so the repeated console prefix no longer has to be stripped. The syslog fallback, which doesn't reassemble, removes the headers and shows the pieces as lines. * fix(ios): bound split-message headers and flush a superseded message The piece header is matched against any entry the NativeScript framework logs, app output included, and its count sized an array up front. A line such as "[ns 1 1/9999999999] x" made that allocation throw and crash the CLI, and a count in the tens of millions stalled the event loop. Headers now only match the digit counts the runtime writes (ids of up to 8 hex digits, counts of up to 7 decimal ones), anything longer passes through as an ordinary message, and pieces are kept by index so a large count costs nothing until pieces actually arrive. When the same id showed up again with a different count, the pending message was replaced but its timer kept running: it later dropped the new message's pieces and printed the old one. The old message is now printed straight away, with its missing pieces marked as lost, and its timer is cleared. * fix(ios): trace what the simulator's log stream writes to stderr With structured simulator logs only stdout was read, so an error from log stream, such as a rejected predicate, disappeared without a trace and the app's logs silently stayed empty. * fix(ios): keep the unique bundle suffix single and honour a global FULL log level The native watcher now passes prepareData when it rewrites the runtime package.json. That write reads main back from the already-emitted file, so with uniqueBundle set an App_Resources change turned "bundle.123" into "bundle.123.123", an entrypoint that doesn't exist. The suffix is only added when main doesn't already carry it. Structured entries decided between the default scope and FULL from the device's own log level only, so setLogLevel("FULL") for all devices, which the syslog path honours, was ignored. They now fall back to the global level the same way. * docs(ios): explain --log levels for device logs Document the levels that scope the app's output in run, debug and test ios, including all, and that --log also makes the CLI's own output verbose. * refactor(ios): drop the startDeviceLogStream availability check ios-device-lib is pinned to 0.10.0, which always has it. Also give IiOSLogEntry and IiOSLogStreamOptions their own doc comments and describe what pid is used for. * feat(visionos): ask for the structured log format in debug builds visionOS devices and simulators already go through the same structured log path as iOS, and the runtime reads logFormat in code shared by both targets. --------- Co-authored-by: Eduardo Speroni <edusperoni@gmail.com> Co-authored-by: Nathan Walker <walkerrunpdx@gmail.com>
1 parent 733e594 commit db4fdaa

22 files changed

Lines changed: 1153 additions & 323 deletions

‎docs/man_pages/project/testing/debug-ios.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Attach the debug tools to a running app in the iOS simulator | `$ ns debug ios -
3030
* `--debug-brk` - Prepares, builds and deploys the application package on a device or in a simulator, runs the app, launches the developer tools of your Safari browser and stops at the first code statement.
3131
* `--start` - Attaches the debug tools to a deployed and running app and launches the developer tools of your Safari browser.
3232
* `--no-client` - If set, the NativeScript CLI attaches the debug tools but does not launch the developer tools in Safari. Could be used on already started Safari Web Inspector.
33+
* `--log <Level>` - Sets how much of the application output is printed. By default only its JavaScript output is shown. `debug` adds everything else the app logs - its native code and the system frameworks it uses, like Xcode's console. `trace` and `all` add debug level entries as well. `--log` also sets the verbosity of the CLI's own output, so each of these levels prints the CLI's diagnostic messages too.
3334
* `--timeout` - Sets the number of seconds that NativeScript CLI will wait to find the inspector socket port from device's logs. If not set, the default timeout is 10 seconds.
3435
* `--no-watch` - If set, changes in your code will not be reflected during the execution of this command.
3536
* `--clean` - If set, forces the complete rebuild of the native application.

‎docs/man_pages/project/testing/run-ios.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ Start an emulator with specified device identifier and sdk | `$ ns run ios [--de
3333
* `--emulator` - If set, runs the app in all available and configured ios simulators. It will start a simulator if none are already running.
3434
* `--sdk` - Specifies the target simulator's sdk.
3535
* `--justlaunch` - If set, does not print the application output in the console.
36+
* `--log <Level>` - Sets how much of the application output is printed. By default only its JavaScript output is shown. `debug` adds everything else the app logs - its native code and the system frameworks it uses, like Xcode's console. `trace` and `all` add debug level entries as well. `--log` also sets the verbosity of the CLI's own output, so each of these levels prints the CLI's diagnostic messages too.
3637
* `--clean` - If set, forces the complete rebuild of the native application.
3738
* `--no-watch` - If set, changes in your code will not be reflected during the execution of this command.
3839
* `--release` - If set, produces a release build by running webpack in production mode and native build in release mode. Otherwise, produces a debug build.

‎docs/man_pages/project/testing/test-ios.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Run tests in the iOS Simulator | `$ ns test ios --emulator [--watch] [--debug-br
2727
* `--device` - Specifies the serial number or the index of the connected device on which you want to run tests. To list all connected devices, grouped by platform, run `$ ns device`. You cannot set `--device` and `--emulator` simultaneously. `<Device ID>` is the device index or identifier as listed by the `$ ns device` command.
2828
* `--emulator` - Runs tests on the iOS Simulator. You cannot set `--device` and `--emulator` simultaneously.
2929
* `--debug-brk` - Runs the tests under the debugger. The debugger will break just before your tests are executed, so you have a chance to place breakpoints.
30+
* `--log <Level>` - Sets how much of the application output is printed. By default only its JavaScript output is shown. `debug` adds everything else the app logs - its native code and the system frameworks it uses, like Xcode's console. `trace` and `all` add debug level entries as well. `--log` also sets the verbosity of the CLI's own output, so each of these levels prints the CLI's diagnostic messages too.
3031
* `--force` - If set, skips the application compatibility checks and forces `npm i` to ensure all dependencies are installed. Otherwise, the command will check the application compatibility with the current CLI version and could fail requiring `ns migrate`.
3132

3233
<% } %>

‎lib/common/constants.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,12 @@ export class EmulatorDiscoveryNames {
6262
}
6363

6464
export const DEVICE_LOG_EVENT_NAME = "deviceLogData";
65+
export const DEVICE_LOG_ENTRY_EVENT_NAME = "deviceLogEntry";
6566
export const IOS_LOG_PREDICATE = 'senderImagePath contains "NativeScript"';
66-
export const IOS_APP_CRASH_LOG_REG_EXP = /Fatal JavaScript exception \- application has been terminated/;
67-
export const FAIL_LIVESYNC_LOG_REGEX = /Failed to refresh the application with RefreshRequest./;
67+
export const IOS_APP_CRASH_LOG_REG_EXP =
68+
/Fatal JavaScript exception \- application has been terminated/;
69+
export const FAIL_LIVESYNC_LOG_REGEX =
70+
/Failed to refresh the application with RefreshRequest./;
6871

6972
export const TARGET_FRAMEWORK_IDENTIFIERS = {
7073
Cordova: "Cordova",

‎lib/common/definitions/mobile.d.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,27 @@ declare global {
151151
): Mobile.IAndroidDeviceHashService;
152152
}
153153

154+
/**
155+
* A structured unified logging (os_log) entry.
156+
*/
157+
interface IiOSLogEntry {
158+
/**
159+
* Scopes the ids of split messages, which are only unique per process.
160+
*/
161+
pid?: number;
162+
thread?: number;
163+
/**
164+
* Path of the executable of the process that logged the entry.
165+
*/
166+
process: string;
167+
/**
168+
* Path of the binary (executable, framework or library) that logged the entry.
169+
*/
170+
image: string;
171+
level: string;
172+
message: string;
173+
}
174+
154175
/**
155176
* Describes log stream options
156177
*/
@@ -213,6 +234,21 @@ declare global {
213234
*/
214235
logData(line: string, platform: string, deviceIdentifier: string): void;
215236

237+
/**
238+
* Logs a structured iOS log entry, when it belongs to the application
239+
* whose logs are shown on the device.
240+
*/
241+
logEntry(
242+
entry: IiOSLogEntry,
243+
platform: string,
244+
deviceIdentifier: string,
245+
): void;
246+
247+
/**
248+
* Returns the project name set for the device, if any.
249+
*/
250+
getProjectNameForDevice(deviceIdentifier: string): string;
251+
216252
/**
217253
* Sets the level of logging that will be used.
218254
* @param {string} level The level of logs - could be INFO or FULL.
@@ -1331,6 +1367,11 @@ declare global {
13311367

13321368
startDeviceLog(deviceIdentifier: string): void;
13331369

1370+
/**
1371+
* Streams structured logs of the process with the given executable name.
1372+
*/
1373+
startDeviceLogStream(deviceIdentifier: string, processName: string): void;
1374+
13341375
apps(
13351376
deviceIdentifiers: string[],
13361377
errorHandler?: DeviceOperationErrorHandler,

‎lib/common/mobile/device-log-emitter.ts‎

Lines changed: 45 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,72 @@ import { DeviceLogProviderBase } from "./device-log-provider-base";
22
import { DEVICE_LOG_EVENT_NAME } from "../constants";
33
import { injector } from "../yok";
44
import * as _ from "lodash";
5+
import { getIOSLogEntryText, getIOSLogScope } from "./ios/ios-log-entry";
56

67
export class DeviceLogEmitter extends DeviceLogProviderBase {
78
constructor(
89
protected $logFilter: Mobile.ILogFilter,
910
$logger: ILogger,
1011
private $loggingLevels: Mobile.ILoggingLevels,
11-
protected $logSourceMapService: Mobile.ILogSourceMapService
12+
protected $logSourceMapService: Mobile.ILogSourceMapService,
1213
) {
1314
super($logFilter, $logger, $logSourceMapService);
1415
}
1516

1617
public logData(
1718
line: string,
1819
platform: string,
19-
deviceIdentifier: string
20+
deviceIdentifier: string,
2021
): void {
2122
this.setDefaultLogLevelForDevice(deviceIdentifier);
2223

2324
const loggingOptions = this.getDeviceLogOptionsForDevice(
24-
deviceIdentifier
25+
deviceIdentifier,
2526
) || { logLevel: this.$loggingLevels.info, projectDir: null };
2627
let data = this.$logFilter.filterData(platform, line, loggingOptions);
2728
data = this.$logSourceMapService.replaceWithOriginalFileLocations(
2829
platform,
2930
data,
30-
loggingOptions
31+
loggingOptions,
3132
);
3233

34+
this.emitData(data, platform, deviceIdentifier);
35+
}
36+
37+
public logEntry(
38+
entry: Mobile.IiOSLogEntry,
39+
platform: string,
40+
deviceIdentifier: string,
41+
): void {
42+
this.stitchIOSLogEntry(entry, deviceIdentifier, (completeEntry) => {
43+
const loggingOptions =
44+
this.getDeviceLogOptionsForDevice(deviceIdentifier);
45+
const text = getIOSLogEntryText(completeEntry, {
46+
processName: loggingOptions && loggingOptions.projectName,
47+
...getIOSLogScope(
48+
this.$logger.getLevel(),
49+
loggingOptions?.logLevel?.toUpperCase() === this.$loggingLevels.full,
50+
),
51+
});
52+
if (text) {
53+
this.emitData(
54+
this.$logSourceMapService.replaceWithOriginalFileLocations(
55+
platform,
56+
text + "\n",
57+
loggingOptions,
58+
),
59+
platform,
60+
deviceIdentifier,
61+
);
62+
}
63+
});
64+
}
65+
66+
private emitData(
67+
data: string,
68+
platform: string,
69+
deviceIdentifier: string,
70+
): void {
3371
if (data) {
3472
this.emit("data", deviceIdentifier, data);
3573
this.emit(DEVICE_LOG_EVENT_NAME, data, deviceIdentifier, platform);
@@ -42,17 +80,16 @@ export class DeviceLogEmitter extends DeviceLogProviderBase {
4280
deviceIdentifier,
4381
(deviceLogOptions: Mobile.IDeviceLogOptions) =>
4482
deviceLogOptions.logLevel,
45-
logLevel.toUpperCase()
83+
logLevel.toUpperCase(),
4684
);
4785
} else {
4886
this.$logFilter.loggingLevel = logLevel.toUpperCase();
4987

5088
_.keys(this.devicesLogOptions).forEach((deviceId) => {
5189
this.devicesLogOptions[deviceId] =
5290
this.devicesLogOptions[deviceId] || <Mobile.IDeviceLogOptions>{};
53-
this.devicesLogOptions[
54-
deviceId
55-
].logLevel = this.$logFilter.loggingLevel;
91+
this.devicesLogOptions[deviceId].logLevel =
92+
this.$logFilter.loggingLevel;
5693
});
5794
}
5895
}

‎lib/common/mobile/device-log-provider-base.ts‎

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,29 @@
11
import { EventEmitter } from "events";
22
import { getPropertyName } from "../helpers";
33
import { IDictionary } from "../declarations";
4+
import { IOSLogChunkStitcher, isIOSRuntimeLogEntry } from "./ios/ios-log-entry";
45

56
export abstract class DeviceLogProviderBase
67
extends EventEmitter
78
implements Mobile.IDeviceLogProvider
89
{
910
protected devicesLogOptions: IDictionary<Mobile.IDeviceLogOptions> = {};
11+
private iOSLogChunkStitcher = new IOSLogChunkStitcher();
1012

1113
constructor(
1214
protected $logFilter: Mobile.ILogFilter,
1315
protected $logger: ILogger,
14-
protected $logSourceMapService: Mobile.ILogSourceMapService
16+
protected $logSourceMapService: Mobile.ILogSourceMapService,
1517
) {
1618
super();
1719
}
1820

1921
public async setSourceFileLocation(
20-
pathToOriginalFile: string
22+
pathToOriginalFile: string,
2123
): Promise<void> {
2224
try {
2325
await this.$logSourceMapService.setSourceMapConsumerForFile(
24-
pathToOriginalFile
26+
pathToOriginalFile,
2527
);
2628
} catch (err) {
2729
this.$logger.trace("Error while trying to set source map file", err);
@@ -31,23 +33,46 @@ export abstract class DeviceLogProviderBase
3133
public abstract logData(
3234
lineText: string,
3335
platform: string,
34-
deviceIdentifier: string
36+
deviceIdentifier: string,
37+
): void;
38+
39+
public abstract logEntry(
40+
entry: Mobile.IiOSLogEntry,
41+
platform: string,
42+
deviceIdentifier: string,
3543
): void;
3644

3745
public abstract setLogLevel(
3846
logLevel: string,
39-
deviceIdentifier?: string
47+
deviceIdentifier?: string,
4048
): void;
4149

50+
protected stitchIOSLogEntry(
51+
entry: Mobile.IiOSLogEntry,
52+
deviceIdentifier: string,
53+
emit: (entry: Mobile.IiOSLogEntry) => void,
54+
): void {
55+
if (!isIOSRuntimeLogEntry(entry)) {
56+
emit(entry);
57+
return;
58+
}
59+
60+
this.iOSLogChunkStitcher.add(
61+
`${deviceIdentifier}:${entry.pid}`,
62+
entry,
63+
emit,
64+
);
65+
}
66+
4267
public setApplicationPidForDevice(
4368
deviceIdentifier: string,
44-
pid: string
69+
pid: string,
4570
): void {
4671
this.setDeviceLogOptionsProperty(
4772
deviceIdentifier,
4873
(deviceLogOptions: Mobile.IDeviceLogOptions) =>
4974
deviceLogOptions.applicationPid,
50-
pid
75+
pid,
5176
);
5277
}
5378

@@ -56,31 +81,31 @@ export abstract class DeviceLogProviderBase
5681
deviceIdentifier,
5782
(deviceLogOptions: Mobile.IDeviceLogOptions) =>
5883
deviceLogOptions.applicationId,
59-
appId
84+
appId,
6085
);
6186
}
6287

6388
public setProjectNameForDevice(
6489
deviceIdentifier: string,
65-
projectName: string
90+
projectName: string,
6691
): void {
6792
this.setDeviceLogOptionsProperty(
6893
deviceIdentifier,
6994
(deviceLogOptions: Mobile.IDeviceLogOptions) =>
7095
deviceLogOptions.projectName,
71-
projectName
96+
projectName,
7297
);
7398
}
7499

75100
public setProjectDirForDevice(
76101
deviceIdentifier: string,
77-
projectDir: string
102+
projectDir: string,
78103
): void {
79104
this.setDeviceLogOptionsProperty(
80105
deviceIdentifier,
81106
(deviceLogOptions: Mobile.IDeviceLogOptions) =>
82107
deviceLogOptions.projectDir,
83-
projectDir
108+
projectDir,
84109
);
85110
}
86111

@@ -99,6 +124,13 @@ export abstract class DeviceLogProviderBase
99124
);
100125
}
101126

127+
public getProjectNameForDevice(deviceIdentifier: string): string {
128+
return (
129+
this.devicesLogOptions[deviceIdentifier] &&
130+
this.devicesLogOptions[deviceIdentifier].projectName
131+
);
132+
}
133+
102134
getApplicationIdForDevice(deviceIdentifier: string) {
103135
return (
104136
this.devicesLogOptions[deviceIdentifier] &&
@@ -107,7 +139,7 @@ export abstract class DeviceLogProviderBase
107139
}
108140

109141
protected getDeviceLogOptionsForDevice(
110-
deviceIdentifier: string
142+
deviceIdentifier: string,
111143
): Mobile.IDeviceLogOptions {
112144
const loggingOptions = this.devicesLogOptions[deviceIdentifier];
113145
if (!loggingOptions) {
@@ -120,7 +152,7 @@ export abstract class DeviceLogProviderBase
120152
protected setDeviceLogOptionsProperty(
121153
deviceIdentifier: string,
122154
propNameFunction: Function,
123-
propertyValue: string | boolean
155+
propertyValue: string | boolean,
124156
): void {
125157
const propertyName = getPropertyName(propNameFunction);
126158

0 commit comments

Comments
 (0)