Skip to content

Commit 745347c

Browse files
feat(ios): show the app's forwarded stdout and stderr (#6181)
* feat(ios): show the app's forwarded stdout and stderr Debug builds ask the runtime to forward stdout and stderr through forwardStdio in the app's package.json. They arrive under the org.nativescript.stdio subsystem and show from --log debug, like the rest of the app's native output and as Xcode's console does, labeled with their stream. * fix(ios): keep forwarded stdio out of the default log scope on the syslog relay When a device falls back to the syslog relay, forwarded stdout and stderr lines arrive as plain text tagged "[org.nativescript.stdio:<stream>]" from the NativeScript image, so the filter let them through at the default --log level and the default scope was no longer JS only. They are now shown from --log debug, as on the structured path, and labeled with their stream the same way. A stdio entry without a category is labeled stdout instead of "undefined", and a test pins the simulator's ndjson subsystem and category fields, since stdio entries missing them would show at the default level. * docs(ios): explain where forwarded stdout and stderr show They show from --log debug up, and stderr is only forwarded on physical devices. * docs(ios): note that forwarded stdout and stderr are debug-build only --------- Co-authored-by: Nathan Walker <walkerrunpdx@gmail.com>
1 parent db4fdaa commit 745347c

12 files changed

Lines changed: 189 additions & 6 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +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.
33+
* `--log <Level>` - Sets how much of the application output is printed. By default only its JavaScript output is shown. `debug` and above add everything else the app logs, like Xcode's console - its native code and the system frameworks it uses, and its standard output and error, such as `print()` output, labeled `stdout:` and `stderr:`. Standard output and error are only forwarded in debug builds, and standard error only on physical devices; in the simulator, `NSLog` output reaches the log without it. `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.
3434
* `--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.
3535
* `--no-watch` - If set, changes in your code will not be reflected during the execution of this command.
3636
* `--clean` - If set, forces the complete rebuild of the native application.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +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.
36+
* `--log <Level>` - Sets how much of the application output is printed. By default only its JavaScript output is shown. `debug` and above add everything else the app logs, like Xcode's console - its native code and the system frameworks it uses, and its standard output and error, such as `print()` output, labeled `stdout:` and `stderr:`. Standard output and error are only forwarded in debug builds, and standard error only on physical devices; in the simulator, `NSLog` output reaches the log without it. `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.
3737
* `--clean` - If set, forces the complete rebuild of the native application.
3838
* `--no-watch` - If set, changes in your code will not be reflected during the execution of this command.
3939
* `--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 & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +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.
30+
* `--log <Level>` - Sets how much of the application output is printed. By default only its JavaScript output is shown. `debug` and above add everything else the app logs, like Xcode's console - its native code and the system frameworks it uses, and its standard output and error, such as `print()` output, labeled `stdout:` and `stderr:`. Standard output and error are only forwarded in debug builds, and standard error only on physical devices; in the simulator, `NSLog` output reaches the log without it. `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.
3131
* `--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`.
3232

3333
<% } %>

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,8 @@ declare global {
170170
image: string;
171171
level: string;
172172
message: string;
173+
subsystem?: string;
174+
category?: string;
173175
}
174176

175177
/**

‎lib/common/mobile/ios/ios-log-entry.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ export function isIOSRuntimeLogEntry(entry: Mobile.IiOSLogEntry): boolean {
3838
return path.basename(entry.image || "") === "NativeScript";
3939
}
4040

41+
// The runtime forwards the app's stdout and stderr under this subsystem, when
42+
// the CLI asks for it through the forwardStdio key of the app's package.json.
43+
export const IOS_STDIO_SUBSYSTEM = "org.nativescript.stdio";
44+
4145
// Logged by the runtime itself on every launch, not by the app.
4246
const RUNTIME_NOISE = ["NativeScript loaded bundle"];
4347

@@ -57,6 +61,12 @@ export function getIOSLogEntryText(
5761
return null;
5862
}
5963

64+
if (entry.subsystem === IOS_STDIO_SUBSYSTEM) {
65+
return options.includeNative
66+
? `${entry.category || "stdout"}: ${entry.message}`
67+
: null;
68+
}
69+
6070
const imageName = path.basename(entry.image || "");
6171
if (isIOSRuntimeLogEntry(entry)) {
6272
return RUNTIME_NOISE.some((noise) => entry.message.includes(noise))

‎lib/common/mobile/ios/simulator/ios-simulator-log-provider.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,8 @@ export class IOSSimulatorLogProvider
148148
image: event.senderImagePath,
149149
level: (event.messageType || "").toLowerCase(),
150150
message: event.eventMessage,
151+
subsystem: event.subsystem,
152+
category: event.category,
151153
},
152154
this.$devicePlatformsConstants.iOS,
153155
deviceId,

‎lib/common/test/unit-tests/mobile/ios-log-entry.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,57 @@ describe("getIOSLogEntryText", () => {
9898
});
9999
});
100100

101+
describe("getIOSLogEntryText for forwarded stdio", () => {
102+
const entry = {
103+
process: "/var/containers/Bundle/Application/X/app.app/app",
104+
image: "/private/Frameworks/NativeScript.framework/NativeScript",
105+
level: "default",
106+
message: "printed",
107+
subsystem: "org.nativescript.stdio",
108+
category: "stdout",
109+
};
110+
111+
it("is hidden by default, unlike the runtime's console output", () => {
112+
assert.isNull(getIOSLogEntryText(entry, { processName: "app" }));
113+
});
114+
115+
it("is labeled with its stream along with native output", () => {
116+
assert.equal(
117+
getIOSLogEntryText(
118+
{ ...entry, category: "stderr" },
119+
{ processName: "app", includeNative: true },
120+
),
121+
"stderr: printed",
122+
);
123+
});
124+
125+
it("is labeled as stdout when it has no category", () => {
126+
assert.equal(
127+
getIOSLogEntryText(
128+
{ ...entry, category: undefined },
129+
{ processName: "app", includeNative: true },
130+
),
131+
"stdout: printed",
132+
);
133+
});
134+
135+
it("is labeled once when a long line was split", () => {
136+
const stitcher = new IOSLogChunkStitcher();
137+
const printed: string[] = [];
138+
for (const message of ["[ns 4 1/2] one", "[ns 4 2/2] two"]) {
139+
stitcher.add("process", { ...entry, message }, (complete) =>
140+
printed.push(
141+
getIOSLogEntryText(complete, {
142+
processName: "app",
143+
includeNative: true,
144+
}),
145+
),
146+
);
147+
}
148+
assert.deepEqual(printed, ["stdout: one two"]);
149+
});
150+
});
151+
101152
describe("getIOSLogScope", () => {
102153
it("maps the CLI log level to the app logs that are shown", () => {
103154
assert.deepEqual(getIOSLogScope("INFO", false), {

‎lib/common/test/unit-tests/mobile/ios-simulator-log-provider.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { PassThrough } from "stream";
44
import { IOSSimulatorLogProvider } from "../../../mobile/ios/simulator/ios-simulator-log-provider";
55
import { DevicePlatformsConstants } from "../../../mobile/device-platforms-constants";
66
import { CommonLoggerStub } from "../stubs";
7+
import { getIOSLogEntryText } from "../../../mobile/ios/ios-log-entry";
78

89
const deviceId = "simulator-id";
910

@@ -66,10 +67,45 @@ describe("IOSSimulatorLogProvider", () => {
6667
image: "/apps/app.app/Frameworks/NativeScript.framework/NativeScript",
6768
level: "default",
6869
message: "CONSOLE LOG: hello",
70+
subsystem: undefined,
71+
category: undefined,
6972
},
7073
]);
7174
});
7275

76+
it("keeps the subsystem and category, so forwarded stdio stays hidden by default", async () => {
77+
await provider.startLogProcess(deviceId);
78+
logProcess.stdout.write(
79+
JSON.stringify({
80+
eventType: "logEvent",
81+
processID: 42,
82+
threadID: 7,
83+
processImagePath: "/apps/app.app/app",
84+
senderImagePath:
85+
"/apps/app.app/Frameworks/NativeScript.framework/NativeScript",
86+
subsystem: "org.nativescript.stdio",
87+
category: "stderr",
88+
messageType: "Default",
89+
eventMessage: "printed",
90+
}) + "\n",
91+
);
92+
await nextTick();
93+
94+
assert.equal(entries.length, 1);
95+
assert.include(entries[0], {
96+
subsystem: "org.nativescript.stdio",
97+
category: "stderr",
98+
});
99+
assert.isNull(getIOSLogEntryText(entries[0], { processName: "app" }));
100+
assert.equal(
101+
getIOSLogEntryText(entries[0], {
102+
processName: "app",
103+
includeNative: true,
104+
}),
105+
"stderr: printed",
106+
);
107+
});
108+
73109
it("traces what log stream writes to stderr", async () => {
74110
await provider.startLogProcess(deviceId);
75111
logProcess.stderr.write("log: Invalid predicate\n");

‎lib/controllers/prepare-controller.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,7 @@ export class PrepareController
537537
!prepareData.release
538538
) {
539539
packageData.logFormat = IOS_LOG_FORMAT;
540+
packageData.forwardStdio = true;
540541
}
541542
if (platform === PlatformTypes.android) {
542543
if (installedRuntimePackageJSON) {

‎lib/services/ios-log-filter.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { injector } from "../common/yok";
2-
import { IOS_LOG_PIECE_HEADER } from "../common/mobile/ios/ios-log-entry";
2+
import * as _ from "lodash";
3+
import {
4+
getIOSLogScope,
5+
IOS_LOG_PIECE_HEADER,
6+
IOS_STDIO_SUBSYSTEM,
7+
} from "../common/mobile/ios/ios-log-entry";
38

49
export class IOSLogFilter implements Mobile.IPlatformLogFilter {
510
// Used to recognize output related to the current project
@@ -28,11 +33,20 @@ export class IOSLogFilter implements Mobile.IPlatformLogFilter {
2833
// lose the header and show as consecutive lines.
2934
private pieceHeaderRegex: RegExp = IOS_LOG_PIECE_HEADER;
3035

36+
// Forwarded stdout and stderr lines carry their subsystem and category in
37+
// front of the text, e.g. "[org.nativescript.stdio:stdout] printed".
38+
private stdioTagRegex: RegExp = new RegExp(
39+
`^\\[${_.escapeRegExp(IOS_STDIO_SUBSYSTEM)}:([^\\]]*)\\](?: |$)`,
40+
);
41+
3142
private filterActive: boolean = true;
3243

3344
private partialLine: string = null;
3445

35-
constructor(private $loggingLevels: Mobile.ILoggingLevels) {}
46+
constructor(
47+
private $loggingLevels: Mobile.ILoggingLevels,
48+
private $logger: ILogger,
49+
) {}
3650

3751
public filterData(
3852
data: string,
@@ -89,6 +103,21 @@ export class IOSLogFilter implements Mobile.IPlatformLogFilter {
89103
currentLine = currentLine.replace(filteredLineInfo[0], "");
90104
}
91105

106+
const stdioTag = this.stdioTagRegex.exec(currentLine);
107+
if (stdioTag) {
108+
// Like the structured logs, stdio shows along with native output.
109+
if (!getIOSLogScope(this.$logger.getLevel(), false).includeNative) {
110+
continue;
111+
}
112+
113+
const text = currentLine
114+
.slice(stdioTag[0].length)
115+
.replace(this.pieceHeaderRegex, "")
116+
.trimEnd();
117+
output += `${stdioTag[1] || "stdout"}: ${text}\n`;
118+
continue;
119+
}
120+
92121
currentLine = currentLine
93122
.replace(this.pieceHeaderRegex, "")
94123
// remove lading space before CONSOLE

0 commit comments

Comments
 (0)