Skip to content

feat(runtime): forward stdout and stderr to os_log for the CLI - #532

Open
rigor789 wants to merge 3 commits into
feat/ios-log-chunksfrom
feat/ios-stdio-forwarding
Open

rigor789 wants to merge 3 commits into
feat/ios-log-chunksfrom
feat/ios-stdio-forwarding

Conversation

@rigor789

@rigor789 rigor789 commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

What is the current behavior?

Without a console, an app's stdio is /dev/null. print() output is lost, and so is NSLog on devices, where it only goes to stderr on iPadOS 26.7. A CLI can't attach to it after launch, because stdio is fixed when the process starts.

What is the new behavior?

In debug builds whose CLI sets forwardStdio in the app's package.json, with stdout still /dev/null, the runtime pipes stdout and stderr into os_log under the org.nativescript.stdio subsystem, with stdout and stderr as categories.

  • Older CLIs never set the key, and release builds and attached consoles fail the checks, so nothing changes for them.
  • stdout becomes line buffered, or print() would wait for a full buffer.
  • Long lines are split the same way as console messages.
  • Devices forward both streams. The simulator forwards stdout only, because NSLog there also reaches the unified log and would print twice. That means fputs(..., stderr) isn't forwarded on the simulator.

Known limits: output buffered at the moment of a crash is lost, so the last lines before an abort() may not appear. An unterminated final line isn't forwarded until a newline arrives or it reaches 64 KB.

Testing

Demo app with Swift code calling print() (short, 5,000 characters, background thread), NSLog and fputs(stderr), on both launches of each run:

Setup Result
New CLI, default, simulator and iPad Hidden, and all 11 console messages intact
New CLI, --log debug, simulator print() shown, 5,000-character line intact, NSLog once (from Foundation)
New CLI, --log debug, iPad (iPadOS 26.7) print(), NSLog and stderr all shown once
Published CLI 9.1.1, simulator No forwarding
simctl launch --console-pty print() goes to the console directly

Older iOS versions weren't tested, and NSLog may behave differently there. A launch from Xcode itself wasn't tested either.

Part of a stack

Base: #530. The CLI side is NativeScript/nativescript-cli#6181.

Summary by CodeRabbit

  • New Features
    • In eligible debug builds, application output written to stdout—and stderr on supported devices—can be forwarded to system logs when enabled in the app configuration. Output is recorded as newline-delimited entries; long lines are also captured in chunks. Forwarding is available only when the app’s output streams meet the required configuration and connection conditions.

@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds configurable log destinations and a stdio forwarder. During runtime initialization, the forwarder checks debug configuration and stdout before redirecting eligible streams to unified logging.

Changes: Logging and stdio forwarding

Layer / File(s) Summary
Log destinations and descriptor checks
NativeScript/runtime/Helpers.h, NativeScript/runtime/Helpers.mm
Logging helpers accept an explicit os_log_t destination. IsDevNull(int fd) is declared in tns and retains its existing implementation.
Conditional stdio forwarding
NativeScript/runtime/StdioForwarder.h, NativeScript/runtime/StdioForwarder.mm
StartStdioForwarding() runs once and checks the debug build, application path, forwardStdio setting, and stdout descriptor. It forwards stdout, and conditionally stderr, through pipes to unified logging.
Runtime and project integration
NativeScript/NativeScript.mm, v8ios.xcodeproj/project.pbxproj
Runtime initialization calls StartStdioForwarding(). The Xcode project includes the forwarder header and implementation in the framework.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Runtime
  participant StartStdioForwarding
  participant Forward
  participant UnifiedLog
  Runtime->>StartStdioForwarding: Call after Runtime::Initialize()
  StartStdioForwarding->>Forward: Redirect eligible stdout and stderr
  Forward->>UnifiedLog: Write newline-delimited output
Loading

Possibly related PRs

Suggested reviewers: edusperoni, nathanwalker

Merge Risk: Low · up to b917f

Forwarding only applies to debug launches started by a CLI that opts in, so other launches are unchanged. In short script-style runs, the last few lines of output may be lost if the app exits right after printing. This is a bounded debug-only limitation and does not block merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: the runtime now forwards app stdout and stderr to os_log when a CLI launch sets forwardStdio. The raw summary confirms new StdioForwarder files, the StartStdioForwardi…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: the runtime now forwards app stdout and stderr to os_log when a CLI launch sets forwardStdio. The raw summary confirms new StdioForwarder files, the StartStdioForwarding() call in NativeScript.mm, and the os_log-related helper changes. The title follows conventional commit style and is specific. It does not cover the Helpers.h/IsDevNull refactor, which is expected.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit taps the log with care,
Then sends stdout through channels there.
Newline by newline, words take flight,
To unified logs in the night.
The rabbit thumps: “Forwarding’s right!”

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bae704a6-d2e9-4366-97a7-a631ada4b5b5
Commits

Reviewing files that changed from the base of the PR and between c839e4a and b917ffb.

Files selected for processing: 4

  • NativeScript/NativeScript.mm
  • NativeScript/runtime/Helpers.h
  • NativeScript/runtime/StdioForwarder.mm
  • v8ios.xcodeproj/project.pbxproj

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

Without a console an app's stdio is /dev/null, so print() and, on devices, NSLog never reach any log stream, and a CLI can't attach to them after launch. In debug builds whose CLI sets forwardStdio in the app's package.json, with stdout still /dev/null, the runtime now pipes them into os_log under the org.nativescript.stdio subsystem. Long lines are split like console messages.
@edusperoni
edusperoni force-pushed the feat/ios-stdio-forwarding branch from c839e4a to 9aa0902 Compare November 11, 2026 18:12

@NathanWalker NathanWalker left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed this PR's own changes on top of #530 (StdioForwarder.mm). The design looks sound:

  • Debug check: "debug" comes from the app's DEBUG through RuntimeConfig.IsDebug, not from the prebuilt framework.
  • Timing: forwarding starts in main() before UIApplicationMain, and setvbuf comes before dup2.
  • LogFormat(): it's warmed up before stdout stops being /dev/null.
  • Writers: the reader takes no locks, so a slow reader only throttles writers.

Two edge cases are worth fixing before merge. I reproduced both with standalone macOS programs.

1. The reader spins at 100% CPU after EOF (StdioForwarder.mm:44-46). if (count <= 0) return; never cancels the source. If the app replaces or closes fd 1/2 after forwarding starts, the pipe's only write end goes away and the read source fires continuously; I measured ~1.4M handler calls/s, each read() returning 0. That can happen through freopen(path, "a+", stderr) (a common way to save NSLog to a file), dup2(file, 1), or close(1).

Suggested fix: on count == 0, or on count < 0 with errno other than EINTR/EAGAIN, flush pending, then dispatch_source_cancel(source), with a cancel handler that closes readEnd.

2. os_log can feed back into the stderr pipe (:91-95). When OS_ACTIVITY_DT_MODE is set, os_log also writes each entry to fd 2. Once stderr is forwarded, the reader's own os_log_with_type goes back into the pipe it's draining. In my test, one fputs("…\n", stderr) produced ~4,900 growing os_log calls. The reader then blocked writing into its own full pipe, and the next main-thread fputs(stderr) hung.

Xcode sets that variable. An Xcode launch probably attaches a pty and fails the /dev/null check, but that wasn't tested. A cheap guard is to skip forwarding stderr when getenv("OS_ACTIVITY_DT_MODE") is set.

Smaller items:

  • 3. A 64 KB flush can cut a UTF-8 character (:57-59). Step back over continuation bytes, as ForEachLogChunk does, and keep the tail in pending.
  • 4. Lines are cut at an embedded NUL (:52, :58), because TNS_WriteToOsLog takes a const char*. A string_view overload would fix that and also avoid the substr() allocation for every line.
  • 5. Mac Catalyst. TARGET_OS_SIMULATOR is 0 on Catalyst, where NSLog also reaches the unified log when stderr is a pipe (checked with log show). So stderr forwarding there would probably print NSLog twice. #if !TARGET_OS_SIMULATOR && !TARGET_OS_MACCATALYST would cover it.
  • 6. Only stdout is checked before stderr is redirected (:76). If stderr points somewhere real, it gets taken over anyway. Adding IsDevNull(STDERR_FILENO) before forwarding fd 2 would fix it.
  • 7. The read source is never released. That's only because the target builds without ARC; under ARC, the source would be freed when Forward returns and nothing would be read. A static or a short comment would stop it breaking silently if this file ever moves to ARC.
  • 8. The commit message for 9aa0902 says non-boolean forwardStdio values are ignored, but isKindOfClass:[NSNumber class] also accepts numbers such as 1. That's harmless; either check CFBooleanGetTypeID() or reword the message.

Question. With --log debug, the printf("Runtime initialization took …") in NativeScript.mm now shows up as a stdout: line on every launch. Is that intended, or should the CLI filter it?

@NathanWalker NathanWalker added this to the 9.2 milestone Nov 21, 2026
- Cancel the read source and close the pipe once read() reports EOF or a
  hard error. After the app replaced or closed fd 1/2 (freopen, dup2,
  close) the source fired continuously at 100% CPU.
- Don't forward stderr while OS_ACTIVITY_DT_MODE is set: os_log then
  copies every entry to stderr, so the forwarder fed its own output back
  into the pipe until it blocked on it.
- Forward stderr only when it is /dev/null too, and not on Mac Catalyst,
  where NSLog already reaches the unified log.
- Cut a line longer than 64 KiB before its last character, so a flush
  never splits a UTF-8 sequence.
- Drop NUL bytes, which ended the os_log string and hid the rest of the
  line. TNS_WriteToOsLog takes a string_view, so lines no longer need a
  substr() copy each.
- Accept only a JSON true for forwardStdio; a number such as 1 enabled it.
@NathanWalker

Copy link
Copy Markdown
Contributor

Pushed b917ffb, which addresses 1–8 from my review:

  1. On EOF or a hard read error, the reader flushes pending, cancels the source and closes the pipe in the cancel handler.
  2. stderr isn't forwarded while OS_ACTIVITY_DT_MODE is set.
  3. A 64 KiB flush cuts before the last character and keeps it in pending.
  4. TNS_WriteToOsLog takes a string_view, so there's no substr() copy. NUL bytes are dropped, because os_log ends %.*s at a NUL even with an explicit length (checked with log show).
    5–6. stderr is forwarded only when it is /dev/null too, and not on Mac Catalyst.
  5. The handler's reference to the source keeps it alive until it is cancelled, under ARC or not.
  6. Only a JSON true enables forwardStdio.

Checked in a macOS harness built from the real StdioForwarder.mm, under both ARC and MRC:

  • After close(1) the reader uses no CPU (0.000 s over 1 s).
  • A 200 KB line of mixed 2-byte, 4-byte and ASCII characters comes out as 66 KB pieces, all valid UTF-8, with no bytes lost.
  • a\0b comes out as ab.
  • No stderr is forwarded when OS_ACTIVITY_DT_MODE is set.

I left the Runtime initialization took… printf as it is.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants