diff --git a/docs/man_pages/project/testing/debug-ios.md b/docs/man_pages/project/testing/debug-ios.md index 59bd8a4fe9..0900bf3481 100644 --- a/docs/man_pages/project/testing/debug-ios.md +++ b/docs/man_pages/project/testing/debug-ios.md @@ -30,7 +30,7 @@ Attach the debug tools to a running app in the iOS simulator | `$ ns debug ios - * `--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. * `--start` - Attaches the debug tools to a deployed and running app and launches the developer tools of your Safari browser. * `--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. -* `--log ` - 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. +* `--log ` - 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. * `--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. * `--no-watch` - If set, changes in your code will not be reflected during the execution of this command. * `--clean` - If set, forces the complete rebuild of the native application. diff --git a/docs/man_pages/project/testing/run-ios.md b/docs/man_pages/project/testing/run-ios.md index 27c93cd503..68a2ed5eb6 100644 --- a/docs/man_pages/project/testing/run-ios.md +++ b/docs/man_pages/project/testing/run-ios.md @@ -33,7 +33,7 @@ Start an emulator with specified device identifier and sdk | `$ ns run ios [--de * `--emulator` - If set, runs the app in all available and configured ios simulators. It will start a simulator if none are already running. * `--sdk` - Specifies the target simulator's sdk. * `--justlaunch` - If set, does not print the application output in the console. -* `--log ` - 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. +* `--log ` - 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. * `--clean` - If set, forces the complete rebuild of the native application. * `--no-watch` - If set, changes in your code will not be reflected during the execution of this command. * `--release` - If set, produces a release build by running webpack in production mode and native build in release mode. Otherwise, produces a debug build. diff --git a/docs/man_pages/project/testing/test-ios.md b/docs/man_pages/project/testing/test-ios.md index ebda39820a..7a38ada938 100644 --- a/docs/man_pages/project/testing/test-ios.md +++ b/docs/man_pages/project/testing/test-ios.md @@ -27,7 +27,7 @@ Run tests in the iOS Simulator | `$ ns test ios --emulator [--watch] [--debug-br * `--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. `` is the device index or identifier as listed by the `$ ns device` command. * `--emulator` - Runs tests on the iOS Simulator. You cannot set `--device` and `--emulator` simultaneously. * `--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. -* `--log ` - 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. +* `--log ` - 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. * `--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`. <% } %> diff --git a/lib/common/definitions/mobile.d.ts b/lib/common/definitions/mobile.d.ts index 4d06a48f6d..92d1280789 100644 --- a/lib/common/definitions/mobile.d.ts +++ b/lib/common/definitions/mobile.d.ts @@ -170,6 +170,8 @@ declare global { image: string; level: string; message: string; + subsystem?: string; + category?: string; } /** diff --git a/lib/common/mobile/ios/ios-log-entry.ts b/lib/common/mobile/ios/ios-log-entry.ts index 2405ce7a26..41d96ad7df 100644 --- a/lib/common/mobile/ios/ios-log-entry.ts +++ b/lib/common/mobile/ios/ios-log-entry.ts @@ -38,6 +38,10 @@ export function isIOSRuntimeLogEntry(entry: Mobile.IiOSLogEntry): boolean { return path.basename(entry.image || "") === "NativeScript"; } +// The runtime forwards the app's stdout and stderr under this subsystem, when +// the CLI asks for it through the forwardStdio key of the app's package.json. +export const IOS_STDIO_SUBSYSTEM = "org.nativescript.stdio"; + // Logged by the runtime itself on every launch, not by the app. const RUNTIME_NOISE = ["NativeScript loaded bundle"]; @@ -57,6 +61,12 @@ export function getIOSLogEntryText( return null; } + if (entry.subsystem === IOS_STDIO_SUBSYSTEM) { + return options.includeNative + ? `${entry.category || "stdout"}: ${entry.message}` + : null; + } + const imageName = path.basename(entry.image || ""); if (isIOSRuntimeLogEntry(entry)) { return RUNTIME_NOISE.some((noise) => entry.message.includes(noise)) diff --git a/lib/common/mobile/ios/simulator/ios-simulator-log-provider.ts b/lib/common/mobile/ios/simulator/ios-simulator-log-provider.ts index 382ba306b0..2cca5e2304 100644 --- a/lib/common/mobile/ios/simulator/ios-simulator-log-provider.ts +++ b/lib/common/mobile/ios/simulator/ios-simulator-log-provider.ts @@ -148,6 +148,8 @@ export class IOSSimulatorLogProvider image: event.senderImagePath, level: (event.messageType || "").toLowerCase(), message: event.eventMessage, + subsystem: event.subsystem, + category: event.category, }, this.$devicePlatformsConstants.iOS, deviceId, diff --git a/lib/common/test/unit-tests/mobile/ios-log-entry.ts b/lib/common/test/unit-tests/mobile/ios-log-entry.ts index 0ed9e7122b..a6f9f930e8 100644 --- a/lib/common/test/unit-tests/mobile/ios-log-entry.ts +++ b/lib/common/test/unit-tests/mobile/ios-log-entry.ts @@ -98,6 +98,57 @@ describe("getIOSLogEntryText", () => { }); }); +describe("getIOSLogEntryText for forwarded stdio", () => { + const entry = { + process: "/var/containers/Bundle/Application/X/app.app/app", + image: "/private/Frameworks/NativeScript.framework/NativeScript", + level: "default", + message: "printed", + subsystem: "org.nativescript.stdio", + category: "stdout", + }; + + it("is hidden by default, unlike the runtime's console output", () => { + assert.isNull(getIOSLogEntryText(entry, { processName: "app" })); + }); + + it("is labeled with its stream along with native output", () => { + assert.equal( + getIOSLogEntryText( + { ...entry, category: "stderr" }, + { processName: "app", includeNative: true }, + ), + "stderr: printed", + ); + }); + + it("is labeled as stdout when it has no category", () => { + assert.equal( + getIOSLogEntryText( + { ...entry, category: undefined }, + { processName: "app", includeNative: true }, + ), + "stdout: printed", + ); + }); + + it("is labeled once when a long line was split", () => { + const stitcher = new IOSLogChunkStitcher(); + const printed: string[] = []; + for (const message of ["[ns 4 1/2] one", "[ns 4 2/2] two"]) { + stitcher.add("process", { ...entry, message }, (complete) => + printed.push( + getIOSLogEntryText(complete, { + processName: "app", + includeNative: true, + }), + ), + ); + } + assert.deepEqual(printed, ["stdout: one two"]); + }); +}); + describe("getIOSLogScope", () => { it("maps the CLI log level to the app logs that are shown", () => { assert.deepEqual(getIOSLogScope("INFO", false), { diff --git a/lib/common/test/unit-tests/mobile/ios-simulator-log-provider.ts b/lib/common/test/unit-tests/mobile/ios-simulator-log-provider.ts index c10015b52c..36e91de8e1 100644 --- a/lib/common/test/unit-tests/mobile/ios-simulator-log-provider.ts +++ b/lib/common/test/unit-tests/mobile/ios-simulator-log-provider.ts @@ -4,6 +4,7 @@ import { PassThrough } from "stream"; import { IOSSimulatorLogProvider } from "../../../mobile/ios/simulator/ios-simulator-log-provider"; import { DevicePlatformsConstants } from "../../../mobile/device-platforms-constants"; import { CommonLoggerStub } from "../stubs"; +import { getIOSLogEntryText } from "../../../mobile/ios/ios-log-entry"; const deviceId = "simulator-id"; @@ -66,10 +67,45 @@ describe("IOSSimulatorLogProvider", () => { image: "/apps/app.app/Frameworks/NativeScript.framework/NativeScript", level: "default", message: "CONSOLE LOG: hello", + subsystem: undefined, + category: undefined, }, ]); }); + it("keeps the subsystem and category, so forwarded stdio stays hidden by default", async () => { + await provider.startLogProcess(deviceId); + logProcess.stdout.write( + JSON.stringify({ + eventType: "logEvent", + processID: 42, + threadID: 7, + processImagePath: "/apps/app.app/app", + senderImagePath: + "/apps/app.app/Frameworks/NativeScript.framework/NativeScript", + subsystem: "org.nativescript.stdio", + category: "stderr", + messageType: "Default", + eventMessage: "printed", + }) + "\n", + ); + await nextTick(); + + assert.equal(entries.length, 1); + assert.include(entries[0], { + subsystem: "org.nativescript.stdio", + category: "stderr", + }); + assert.isNull(getIOSLogEntryText(entries[0], { processName: "app" })); + assert.equal( + getIOSLogEntryText(entries[0], { + processName: "app", + includeNative: true, + }), + "stderr: printed", + ); + }); + it("traces what log stream writes to stderr", async () => { await provider.startLogProcess(deviceId); logProcess.stderr.write("log: Invalid predicate\n"); diff --git a/lib/controllers/prepare-controller.ts b/lib/controllers/prepare-controller.ts index 981873b048..1210c316d4 100644 --- a/lib/controllers/prepare-controller.ts +++ b/lib/controllers/prepare-controller.ts @@ -537,6 +537,7 @@ export class PrepareController !prepareData.release ) { packageData.logFormat = IOS_LOG_FORMAT; + packageData.forwardStdio = true; } if (platform === PlatformTypes.android) { if (installedRuntimePackageJSON) { diff --git a/lib/services/ios-log-filter.ts b/lib/services/ios-log-filter.ts index 6b5c5d53fe..4b5c3662c5 100644 --- a/lib/services/ios-log-filter.ts +++ b/lib/services/ios-log-filter.ts @@ -1,5 +1,10 @@ import { injector } from "../common/yok"; -import { IOS_LOG_PIECE_HEADER } from "../common/mobile/ios/ios-log-entry"; +import * as _ from "lodash"; +import { + getIOSLogScope, + IOS_LOG_PIECE_HEADER, + IOS_STDIO_SUBSYSTEM, +} from "../common/mobile/ios/ios-log-entry"; export class IOSLogFilter implements Mobile.IPlatformLogFilter { // Used to recognize output related to the current project @@ -28,11 +33,20 @@ export class IOSLogFilter implements Mobile.IPlatformLogFilter { // lose the header and show as consecutive lines. private pieceHeaderRegex: RegExp = IOS_LOG_PIECE_HEADER; + // Forwarded stdout and stderr lines carry their subsystem and category in + // front of the text, e.g. "[org.nativescript.stdio:stdout] printed". + private stdioTagRegex: RegExp = new RegExp( + `^\\[${_.escapeRegExp(IOS_STDIO_SUBSYSTEM)}:([^\\]]*)\\](?: |$)`, + ); + private filterActive: boolean = true; private partialLine: string = null; - constructor(private $loggingLevels: Mobile.ILoggingLevels) {} + constructor( + private $loggingLevels: Mobile.ILoggingLevels, + private $logger: ILogger, + ) {} public filterData( data: string, @@ -89,6 +103,21 @@ export class IOSLogFilter implements Mobile.IPlatformLogFilter { currentLine = currentLine.replace(filteredLineInfo[0], ""); } + const stdioTag = this.stdioTagRegex.exec(currentLine); + if (stdioTag) { + // Like the structured logs, stdio shows along with native output. + if (!getIOSLogScope(this.$logger.getLevel(), false).includeNative) { + continue; + } + + const text = currentLine + .slice(stdioTag[0].length) + .replace(this.pieceHeaderRegex, "") + .trimEnd(); + output += `${stdioTag[1] || "stdout"}: ${text}\n`; + continue; + } + currentLine = currentLine .replace(this.pieceHeaderRegex, "") // remove lading space before CONSOLE diff --git a/test/controllers/prepare-controller.ts b/test/controllers/prepare-controller.ts index 554f8cafa4..cb784b9b65 100644 --- a/test/controllers/prepare-controller.ts +++ b/test/controllers/prepare-controller.ts @@ -200,11 +200,14 @@ describe("prepareController", () => { assert.equal(rewritten.main, "bundle.123"); }); - it("asks for the structured log format in iOS and visionOS debug builds only", async () => { + it("asks for the structured log format and stdio in iOS and visionOS debug builds only", async () => { assert.equal((await writePackageJson("ios", false)).logFormat, 1); assert.equal((await writePackageJson("visionos", false)).logFormat, 1); assert.isUndefined((await writePackageJson("ios", true)).logFormat); assert.isUndefined((await writePackageJson("visionos", true)).logFormat); + assert.isTrue((await writePackageJson("ios", false)).forwardStdio); + assert.isTrue((await writePackageJson("visionos", false)).forwardStdio); + assert.isUndefined((await writePackageJson("ios", true)).forwardStdio); assert.isUndefined((await writePackageJson("android", false)).logFormat); }); }); diff --git a/test/services/ios-log-filter.ts b/test/services/ios-log-filter.ts index 038597cd80..11a3fee315 100644 --- a/test/services/ios-log-filter.ts +++ b/test/services/ios-log-filter.ts @@ -209,6 +209,55 @@ describe("iOSLogFilter", () => { ); }); + describe("forwarded stdio", () => { + const deviceHeader = + "\u0000Oct 29 20:20:54 iPad app(NativeScript)[1514] : "; + const simulatorHeader = + "2017-10-09 13:34:38.527844+0300 localhost app[52946]: (NativeScript) "; + const lines = [ + `${deviceHeader}[org.nativescript.stdio:stdout] printed\n`, + `${deviceHeader}[org.nativescript.stdio:stderr] logged\n`, + `${deviceHeader}[org.nativescript.stdio:stdout] [ns 2 1/2] long\n`, + `${deviceHeader}[org.nativescript.stdio:stdout] [ns 2 2/2] line\n`, + `${simulatorHeader}[org.nativescript.stdio:stdout] simulated\n`, + `${deviceHeader}CONSOLE LOG: js\n`, + ]; + const filter = (cliLogLevel: string) => { + testInjector = createTestInjector("app"); + testInjector.resolve("logger").getLevel = () => cliLogLevel; + logFilter = testInjector.resolve(IOSLogFilter); + return lines + .map((line) => + logFilter.filterData(line, { + logLevel: infoLogLevel, + projectName: "app", + }), + ) + .filter(Boolean) + .join(""); + }; + + it("is hidden by default", () => { + assert.strictEqual(filter(undefined), "CONSOLE LOG: js\n"); + assert.strictEqual(filter("INFO"), "CONSOLE LOG: js\n"); + }); + + it("shows from --log debug, labeled with its stream", () => { + assert.strictEqual( + filter("DEBUG"), + [ + "stdout: printed", + "stderr: logged", + "stdout: long", + "stdout: line", + "stdout: simulated", + "CONSOLE LOG: js", + "", + ].join("\n"), + ); + }); + }); + it("drops other processes' lines that have no image name, such as the kernel's", () => { testInjector = createTestInjector("nsconsoletablet"); logFilter = testInjector.resolve(IOSLogFilter);