Skip to content

refactor(logging): replace console.* with Winston logger across server files#268

Closed
Muneerali199 wants to merge 2 commits into
AOSSIE-Org:mainfrom
Muneerali199:refactor/server-logging
Closed

refactor(logging): replace console.* with Winston logger across server files#268
Muneerali199 wants to merge 2 commits into
AOSSIE-Org:mainfrom
Muneerali199:refactor/server-logging

Conversation

@Muneerali199
Copy link
Copy Markdown
Contributor

@Muneerali199 Muneerali199 commented Mar 8, 2026

Summary

Closes #213

All raw console.* calls in server-side modules have been replaced with explicit Winston logger calls. The global monkey-patch in logger.ts (which silently re-routed console.log/console.error but left console.warn/console.info unpatched) has been removed in favour of each module importing the logger directly.

Changes

src/utils/logger.ts

  • Remove console.log / console.error monkey-patch and the dead _originalConsoleLog / _originalConsoleError variables.
  • Each server module now owns its logging explicitly — no hidden global side-effects.

src/server/websocket.ts

  • Remove duplicate console.error("WebSocket error:", error) on the ws.on("error") handler; logger.error was already called on the same line.
  • Downgrade high-frequency "Upgrade request received" log from infodebug to reduce noise in production logs.

src/server/InputHandler.ts

  • Import logger from ../utils/logger.
  • Replace all 16 raw console.log / console.warn / console.error calls with logger.debug / logger.warn / logger.error respectively.
  • Fix mislabeled error message in the scroll-throttle path: "Error processing pending move event""Error processing pending scroll event".
  • Downgrade operational trace logs (key processing, combo press/complete) from console.log to logger.debug.

src/server/ydotool.ts

  • Import logger.
  • Replace 3 console.* calls. Notably, the console.warn fallback message was previously unpatched by the monkey-patch and silently dropped to native stderr — it now reaches the log file.

src/server/tokenStore.ts

  • Import logger.
  • Replace console.error("Failed to persist tokens:", e) with logger.error(...).

What was NOT changed

  • electron/main.cjs — separate OS process with no Winston access; its console.log calls are intentional.
  • Client-side files (src/hooks/, src/routes/) — browser context, out of scope.
  • test-input.ts — standalone test script, out of scope.

Summary by CodeRabbit

  • Bug Fixes

    • Improved mouse movement handling with a fallback to absolute positioning when relative moves fail.
  • Chores

    • Standardized application logging to a centralized logger for clearer diagnostics and consistent messages.
    • Restored default console behavior (console output no longer intercepted), while retaining structured logger outputs.

…r files

- src/utils/logger.ts: remove console.log/console.error monkey-patch and
  dead _originalConsoleLog/_originalConsoleError variables; each server
  module now imports logger explicitly, making log routing predictable
- src/server/websocket.ts: remove duplicate console.error on ws 'error'
  event (logger.error was already called on same line); downgrade
  high-frequency 'Upgrade request received' log from info to debug
- src/server/InputHandler.ts: import logger; replace 16 raw console.*
  calls with logger.error/warn/debug as appropriate; fix mislabeled
  error message in scroll throttle path ('move' -> 'scroll'); downgrade
  operational key/combo trace logs to debug level
- src/server/ydotool.ts: import logger; replace 3 console.* calls;
  console.warn was previously unpatched and silently lost to stderr
- src/server/tokenStore.ts: import logger; replace console.error
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 8, 2026

Walkthrough

Server-side logging was migrated from direct console.* calls to a centralized logger across InputHandler, tokenStore, websocket, and ydotool modules; the logger utility's global console interception was removed. InputHandler's mouse move now tries a ydotool relative move and falls back to absolute positioning on failure.

Changes

Cohort / File(s) Summary
Logger core
src/utils/logger.ts
Removed interception/overrides of console.log and console.error; retained Winston transports — console calls now go to default behavior while code uses the centralized logger.
Input handling
src/server/InputHandler.ts
Replaced console.* with logger calls across error/warn/debug paths; move handling now attempts ydotool relative move first and falls back to absolute positioning using current mouse + delta; expanded logging for key, combo, text, click, copy/paste, scroll, and throttling/error flows.
Ydotool integration
src/server/ydotool.ts
Replaced console.* with logger for detection, warnings, and errors; moveRelative now returns false on failure and logs errors via logger.
Token & WebSocket
src/server/tokenStore.ts, src/server/websocket.ts
Replaced console.error/console.log with logger.error/logger.debug; downgraded WebSocket upgrade informational log to debug.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant InputHandler
  participant YDotool
  participant OS_Mouse
  participant Logger

  Client->>InputHandler: send move(delta)
  InputHandler->>YDotool: attempt moveRelative(delta)
  YDotool-->>InputHandler: success / failure
  alt success
    InputHandler->>Logger: debug move succeeded (ydotool)
  else failure
    InputHandler->>OS_Mouse: compute absolute from currentPos + delta and move
    OS_Mouse-->>InputHandler: success / failure
    InputHandler->>Logger: warn/error with context
  end
  InputHandler->>Logger: debug completion or throttled warning
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

Typescript Lang

Poem

🐰 I hop through logs both bright and dim,
Replacing consoles with a steady vim,
If ydotool stumbles I hop to a plan,
Move by delta then absolute, as only a rabbit can. 🥕

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: replacing console logging with Winston logger across server files.
Description check ✅ Passed The PR description provides detailed explanation of changes across all modified files, clearly maps to issue #213, and documents intentional exclusions.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #213: removes console.* logging, cleans up websocket.ts duplicates, reduces noise by downgrading log levels, and removes sensitive data logging.
Out of Scope Changes check ✅ Passed All changes are directly scoped to requirements in issue #213; modifications are limited to server-side logging refactoring in five files with clear intentional exclusions documented.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/server/InputHandler.ts (1)

277-296: ⚠️ Potential issue | 🟠 Major

Stop logging raw key input and combo contents.

These debug/warn lines write actual keystrokes and shortcut contents into the server logs. Because single-character input is handled through msg.key, a password or token entered over the remote-control channel will be reconstructed in the logs one event at a time. Log only redacted metadata here.

🛡️ Proposed fix
-					logger.debug(`Processing key: ${msg.key}`)
+					logger.debug("Processing key input")
...
-							logger.debug(`Unmapped key: ${msg.key}`)
+							logger.debug("Unmapped key received")
...
-							logger.warn(`Unknown key in combo: ${k}`)
+							logger.warn("Unknown key in combo")
...
-					logger.debug(`Pressing keys: ${nutKeys.join(", ")}`)
+					logger.debug(`Pressing combo with ${nutKeys.length} accepted keys`)
...
-					logger.debug(`Combo complete: ${msg.keys.join("+")}`)
+					logger.debug(`Combo complete (${nutKeys.length} accepted keys)`)
As per coding guidelines, "No exposed API keys or sensitive data".

Also applies to: 324-358

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server/InputHandler.ts` around lines 277 - 296, Replace any logs that
include raw keystroke or combo contents (e.g., the logger.debug calling
`Processing key: ${msg.key}`, the `logger.debug('Unmapped key: ${msg.key}')` and
the `logger.warn` that prints the error context including `msg.key`) so they
never emit plaintext `msg.key` or reconstructed combos; instead log only
non-sensitive metadata (e.g., event type, message length, redacted placeholder
like "<REDACTED_KEY>", or a hashed/length indicator). Update the key-handling
block around the `nutKey = KEY_MAP[msg.key.toLowerCase()]`, `keyboard.pressKey`,
`keyboard.releaseKey`, and `keyboard.type(msg.key)` paths to remove direct
`msg.key` interpolation in logs and apply the same redaction strategy to the
similar logging in the subsequent combo handling section (the code referenced at
lines ~324-358). Ensure error logs still capture useful context but never
include the raw `msg.key` contents.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/server/ydotool.ts`:
- Around line 36-41: The warning currently flattens all errors into "ydotool not
available"; update the catch block that handles execFileAsync("which",
["ydotool"]) so it logs the actual failure reason by including the caught error
(err) in the logger.warn call (alongside the existing message), while still
setting isYdotoolAvailable = false and lastFailureTime = now; reference the
variables isYdotoolAvailable, lastFailureTime and the logger.warn invocation in
src/server/ydotool.ts to find and modify the catch body.

---

Outside diff comments:
In `@src/server/InputHandler.ts`:
- Around line 277-296: Replace any logs that include raw keystroke or combo
contents (e.g., the logger.debug calling `Processing key: ${msg.key}`, the
`logger.debug('Unmapped key: ${msg.key}')` and the `logger.warn` that prints the
error context including `msg.key`) so they never emit plaintext `msg.key` or
reconstructed combos; instead log only non-sensitive metadata (e.g., event type,
message length, redacted placeholder like "<REDACTED_KEY>", or a hashed/length
indicator). Update the key-handling block around the `nutKey =
KEY_MAP[msg.key.toLowerCase()]`, `keyboard.pressKey`, `keyboard.releaseKey`, and
`keyboard.type(msg.key)` paths to remove direct `msg.key` interpolation in logs
and apply the same redaction strategy to the similar logging in the subsequent
combo handling section (the code referenced at lines ~324-358). Ensure error
logs still capture useful context but never include the raw `msg.key` contents.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e5bd1219-32ed-4b65-82c0-899f5d425df0

📥 Commits

Reviewing files that changed from the base of the PR and between 56775a5 and afaa8b0.

📒 Files selected for processing (5)
  • src/server/InputHandler.ts
  • src/server/tokenStore.ts
  • src/server/websocket.ts
  • src/server/ydotool.ts
  • src/utils/logger.ts
💤 Files with no reviewable changes (1)
  • src/utils/logger.ts

Comment thread src/server/ydotool.ts
…otool warn

- InputHandler.ts: remove raw msg.key and combo key values from debug/warn
  log messages to prevent accidental keystroke capture (e.g. passwords typed
  over the remote channel); log only non-sensitive metadata instead
- ydotool.ts: include caught error message in the 'ydotool not available'
  warning so the actual failure reason is visible in logs
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/server/InputHandler.ts`:
- Around line 90-92: The logger.error calls in InputHandler (multiple locations
shown) and ydotool.ts are interpolating err.message into strings which strips
stack/structured info; update each occurrence (the logger.error(...) calls
around the pending move handling and the other listed line groups) to pass the
original Error object as the first argument (and any metadata as the second
argument, e.g., { context: "pendingMove" } or similar) so Winston can preserve
stack traces and structured error details; search for the pattern
logger.error(`Error...${err instanceof Error ? err.message : String(err)}`) and
replace it by passing err directly to logger.error(err, { /* metadata */ }) in
the relevant functions/methods in InputHandler and the error log in ydotool.ts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: bcfd50fa-c087-4199-a512-58b348a40f7d

📥 Commits

Reviewing files that changed from the base of the PR and between afaa8b0 and 64c62ed.

📒 Files selected for processing (2)
  • src/server/InputHandler.ts
  • src/server/ydotool.ts

Comment on lines +90 to +92
logger.error(
`Error processing pending move event: ${err instanceof Error ? err.message : String(err)}`,
)
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.

🧹 Nitpick | 🔵 Trivial

🧩 Analysis chain

🌐 Web query:

For Winston 3.x using format.errors({ stack: true }), what is the recommended way to log a caught Error while preserving its stack trace and metadata, instead of interpolating err.message into the log message string?

💡 Result:

With format.errors({ stack: true }) enabled, pass the actual Error instance to Winston, and put any extra context/metadata in the second argument (or as extra fields on an info object). The errors() formatter is designed to detect an Error and copy its .message (and .stack when stack: true) onto the log info. [1]

try {
  // ...
} catch (err) {
  logger.error(err, { requestId, userId, op: "doThing" }); // keeps stack + metadata
}

Alternative (same idea, using an info object):

logger.error({ message: err, requestId, userId, op: "doThing" });

Both patterns avoid interpolating err.message into a string and preserve the stack trace via format.errors({ stack: true }). [1][2]

Sources:
[1] logform errors format docs (allows passing an Error directly; adds stack when enabled) (github.com)
[2] Example usage showing logger.error(new Error(...), { ...meta }) / logger.error({ message: new Error(...), ... }) (app.unpkg.com)

Citations:


🏁 Script executed:

# First, verify the files exist and check their sizes
wc -l src/server/InputHandler.ts src/utils/logger.ts src/server/ydotool.ts 2>/dev/null || echo "Some files may not exist"

Repository: AOSSIE-Org/Rein

Length of output: 157


🏁 Script executed:

# Check the specific lines mentioned in InputHandler.ts
head -100 src/server/InputHandler.ts | tail -20

Repository: AOSSIE-Org/Rein

Length of output: 649


🏁 Script executed:

# Check the logger configuration
cat -n src/utils/logger.ts | head -50

Repository: AOSSIE-Org/Rein

Length of output: 1985


🏁 Script executed:

# Check all flagged lines in InputHandler.ts
cat -n src/server/InputHandler.ts | sed -n '88,114p'

Repository: AOSSIE-Org/Rein

Length of output: 1108


🏁 Script executed:

# Check other flagged line ranges
cat -n src/server/InputHandler.ts | sed -n '145,150p;169,174p;183,188p;198,204p;238,244p;292,298p;346,352p;365,371p'

Repository: AOSSIE-Org/Rein

Length of output: 2050


🏁 Script executed:

# Check ydotool.ts for similar error logging patterns
cat -n src/server/ydotool.ts

Repository: AOSSIE-Org/Rein

Length of output: 2612


Pass Error objects directly to logger instead of interpolating error messages.

Interpolating err.message into template literals discards the original Error, preventing format.errors({ stack: true }) from preserving stack traces and structured error details. Pass the Error object directly; Winston will extract the message and stack automatically.

This applies to multiple locations: InputHandler.ts lines 90–92, 111–113, 147–149, 171–173, 185–187, 200–202, 240–242, 294–296, 348–350, 367–369, and ydotool.ts line 70–72.

Current pattern (incorrect):

logger.error(`Error: ${err instanceof Error ? err.message : String(err)}`)

Correct pattern:

logger.error(err, { context: "additional metadata" })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/server/InputHandler.ts` around lines 90 - 92, The logger.error calls in
InputHandler (multiple locations shown) and ydotool.ts are interpolating
err.message into strings which strips stack/structured info; update each
occurrence (the logger.error(...) calls around the pending move handling and the
other listed line groups) to pass the original Error object as the first
argument (and any metadata as the second argument, e.g., { context:
"pendingMove" } or similar) so Winston can preserve stack traces and structured
error details; search for the pattern logger.error(`Error...${err instanceof
Error ? err.message : String(err)}`) and replace it by passing err directly to
logger.error(err, { /* metadata */ }) in the relevant functions/methods in
InputHandler and the error log in ydotool.ts.

@imxade imxade closed this Mar 8, 2026
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.

Refactor Server-Side Logging

2 participants