Skip to content

refactor: replace console.error with structured logError from telemetry module - #295

Closed
aadityakumarsah wants to merge 4 commits into
modelence:mainfrom
aadityakumarsah:fix/structured-logging
Closed

aadityakumarsah wants to merge 4 commits into
modelence:mainfrom
aadityakumarsah:fix/structured-logging

Conversation

@aadityakumarsah

@aadityakumarsah aadityakumarsah commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Replaces ad-hoc console.error calls with logError from the telemetry module so errors are logged as a message plus a structured context object (e.g. { error, methodName, path, alias }) instead of string concatenation.

Coverage spans app startup (cloud connect, cron startup, background indexes/migrations), HTTP (unhandled rejections/exceptions, method and route handler failures), auth (OAuth providers, magic link, password reset landing, email verification), infra (MongoDB connect, config sync, cron jobs, Socket.IO, live-query handlers, store index creation), and related tests/mocks. bin/, client/, and viteServer.ts are intentionally left alone (CLI/dev-server output).

Telemetry changes

  • logError normalizes Error instances into { message, stack, name } before the payload is sent to the remote (Elastic) sink, so stack traces survive JSON serialization (previously Errors serialized to {}).
  • logError applies redactSensitive (token/password/secret/nonce/code keys) to the payload shipped to the remote sink; console output keeps raw values for local debugging.
  • Console logging behavior is unchanged and matches the documented contract: telemetry enabled + no MODELENCE_LOG_LEVEL ⇒ no console logging.

Notes

  • All context objects use the consistent { error } key (unhandled rejections previously used { reason, promise }; the promise field serialized to {} and was dropped).
  • Test mocks for logError are now distinct from logInfo so assertions can fail correctly.

Note

Medium Risk
Broad logging refactor plus auth validation and cron scheduling/persistence behavior; changes are mostly observability and edge cases but touch critical startup and sign-in paths.

Overview
Replaces scattered console.error calls with logError from the telemetry module so failures are recorded as a message plus structured context (e.g. { error, methodName, path, alias }) across app startup, HTTP handlers, auth, MongoDB, config sync, cron, Socket.IO, live queries, and store index creation.

Telemetry: logError now normalizes Error values for the Elastic sink ({ message, stack, name }), redacts sensitive keys on the remote path only, and uses shouldLogToConsole so startup errors still print when telemetry is on but the Winston logger is not ready yet. Tests and mocks were updated for the new call shape.

Auth: Password login and signup reject requests when a user is already authenticated with ValidationError and code ALREADY_AUTHENTICATED, before rate limits or DB work. ValidationError accepts an optional code (surfaced like other ModelenceError codes where applicable).

Cron: startCronJobs no-ops when MongoDB URI is missing; job runs persist lastStartDate via upsertOne (with $setOnInsert) instead of updateOne.

Smaller changes: NPM publish workflow tags non-dev prereleases as next; magic-link docs note availability since [email protected].

Reviewed by Cursor Bugbot for commit dd8fa73. Bugbot is set up for automated code reviews on this repo. Configure here.

Comment thread packages/modelence/src/auth/session.ts Resolved
Comment thread packages/modelence/src/app/metrics.ts Resolved
Comment thread packages/modelence/src/db/client.ts Resolved
Comment thread packages/modelence/src/app/server.ts Resolved
Comment thread packages/modelence/src/app/metrics.ts Resolved
Comment thread packages/modelence/src/app/index.ts Resolved
@omegascorp

Copy link
Copy Markdown
Collaborator

@aadityakumarsah please check bugbot findings it did a decent job

aadityakumarsah added a commit to aadityakumarsah/modelence that referenced this pull request Jul 17, 2026
Comment thread packages/modelence/src/app/metrics.ts Resolved
@omegascorp

Copy link
Copy Markdown
Collaborator

@aadityakumarsah this contains extra changes from commit: c1bdb02

Please remove it and resolve the conflicts

…dule

console.error bypasses the winston-based telemetry layer. All production
code paths that log errors now use the existing logError() utility which
routes through winston (when available) while still falling back to
console.error when telemetry is not configured.

Files changed:
  src/app/backendApi.ts, src/app/index.ts, src/app/metrics.ts,
  src/app/server.ts, src/auth/providers/github.ts,
  src/auth/providers/google.ts, src/auth/providers/oauth-common.ts,
  src/auth/resetPassword.ts, src/auth/verification.ts,
  src/config/sync.ts, src/cron/jobs.ts, src/db/client.ts,
  src/migration/index.ts, src/routes/handler.ts,
  src/websocket/socketio/server.ts

Test update files:
  src/app/backendApi.test.ts, src/app/server.test.ts,
  src/cron/jobs.test.ts, src/db/client.test.ts,
  src/migration/index.test.ts, src/routes/handler.test.ts
@aadityakumarsah
aadityakumarsah force-pushed the fix/structured-logging branch from 7e1641b to f107033 Compare July 22, 2026 12:44
@omegascorp

Copy link
Copy Markdown
Collaborator

Hi @aadityakumarsah, please check the following points; they are generated by AI based on the points I've aked to highlight

  1. Is the architecture correct?
    Direction: yes. Execution: no — the telemetry change at the center of it is wrong.

Routing errors through a telemetry facade instead of console.error is the right call, and the call-site conversions are mostly clean. But the PR bundles three unrelated things under one "structured logging" banner, and the riskiest one is the smallest diff:

(a) The isLoggerReady bypass in telemetry/index.ts:52-73 is a real bug, not a safety net.

The stated goal is "errors aren't dropped during bootstrap." But look at what startLoggerProcess already does — loggerProcess.ts:24-36 monkey-patches process.stdout.write and process.stderr.write, buffers everything, and then ships it via logInfo/logError on a 1s loop (loggerProcess.ts:96-109).

So once the logger is ready, every console.error becomes a logError call, which writes to console, which the patched stderr.write captures, which buffers it for the next sendLogs tick. The new condition doesn't fire in that state (isLoggerReady() is true), so it doesn't create an infinite loop today — but it is one isLoggerReady refactor away from being one, and the PR adds no comment or test marking that hazard. The existing architecture deliberately separates "console output" from "logger output" precisely because the two are wired together. Widening the console branch on a readiness condition is editing a load-bearing wall.

(b) The condition contradicts the module's documented contract. telemetry/index.ts:29-38 explicitly documents: telemetry enabled + no MODELENCE_LOG_LEVEL ⇒ '' ⇒ no console logging. That's an intentional design decision — telemetry-enabled deployments send to Elastic, not stdout. The PR overrides it via a side condition without touching the docblock, so the code and its own documentation now disagree.

(c) The winston.format.errors({ stack: true }) change is a no-op as written. In metrics.ts:86, that formatter extracts .stack from an Error passed as the log message (logger.error(errorInstance)). Every converted call site passes the error as a meta field: logError('...', { error }). The message is a string, so errors() never engages, and winston.format.json() serializes the nested Error to {} — Error has no enumerable own properties. Net effect: this PR loses stack traces rather than gaining them, which is the exact opposite of the PR's claim.

That regression is most visible in server.ts:172-174. The old code printed error.stack plus console.trace. The new logError('Uncaught Exception', { error }) serializes to {"error":{}} on the Elastic path. For an uncaught exception handler, that's a meaningful loss of debuggability.

  1. Can the code be simplified?
    Yes, substantially.

The repeated (isTelemetryEnabled() && !isLoggerReady()) clause is copy-pasted three times. Even if the behavior were desirable, it belongs in one predicate:

function shouldLogToConsole(level: Exclude<LogLevel, ''>): boolean {
const enabledLevels = { error: ['debug','info','error'], info: ['debug','info'], debug: ['debug'] };
return enabledLevels[level].includes(getLogLevel());
}
The error-serialization problem should be fixed once, centrally, not per call site — normalize in logError itself:

export function logError(message: string, args: object) {
const normalized = 'error' in args && args.error instanceof Error
? { ...args, error: { message: args.error.message, stack: args.error.stack, name: args.error.name } }
: args;
// ...
}
That single change makes the winston.format.errors edit unnecessary and actually delivers the stated goal.

redactSensitive is not applied. It exists at telemetry/index.ts:14 and is used in methods/index.ts and routes/handler.ts, but logError doesn't call it. Several new call sites now push richer context into telemetry — { path: req.path, error } in routes/handler.ts:81 and OAuth errors in github.ts:177 / google.ts:125. OAuth error objects routinely carry code and token values in nested response bodies, and SENSITIVE_KEYS already lists both. Sending those to Elastic unredacted is a genuine concern, and it's newly introduced here: console.error stayed local, logError ships to a remote sink.

  1. Technical issues
    Beyond the above:

logError is called before telemetry is initialized — the PR's own premise is inverted. In backendApi.ts:74, connectCloudBackend is what produces the telemetry metadata. Tracing app/index.ts:154-196: connectCloudBackend() → setMetadata() → initMetrics(). So when the cloud connection fails, isTelemetryEnabled() is still false (metadata never set), getLogLevel() returns 'info', and it prints to console. It works — but by falling through the disabled-telemetry path, not the new bootstrap branch. The new condition does nothing for the one call site that most motivated it.

Test quality is poor and hides regressions:

server.test.ts:109 and migration/index.test.ts:16 alias logError: mockLogInfo — the same mock for both functions. A test asserting logError was called now passes if logInfo was called instead. That's an assertion that cannot fail correctly.
metrics.test.ts:72 adds errors: vi.fn() purely to stop the mock from throwing. Nothing verifies the formatter is wired correctly — which is exactly why issue (c) went unnoticed.
No test covers the new !isLoggerReady() branch. The central behavioral change of the PR is untested. Worse, the existing test at telemetry/index.test.ts:184-194 — "logError does not log to console when log level is not set" — only still passes because it sets isLoggerReady to true. Flip that mock and the new code breaks the documented contract, with no test noticing.
Inconsistent context keys. server.ts:165-168 uses { reason, promise } while everything else uses { error }. Also, promise is a Promise object — it JSON-serializes to {}, so it's dead weight in the payload. And reason is pre-stringified to .stack there while other sites pass raw errors, so the shape varies across sites in a way that defeats structured querying.

Scope is inconsistent. ~70 console.error calls remain, including migration/index.ts:112-adjacent paths, all of live-query/handlers.ts, magicLink.ts (same auth module as converted files), and data/store.ts:725. Server-side magicLink.ts sitting unconverted next to a converted resetPassword.ts is hard to justify — though bin/, client/, and viteServer.ts are correctly left alone.

Minor: the PR title says fix: but this is refactor:/chore: — no user-facing bug is fixed. The body is literally "test".

  1. Is the change actually required?
    The call-site refactor: yes, worth doing. Structured logging with queryable fields (methodName, path, alias) is a genuine improvement over string concatenation, and it's the kind of consistency a framework should have.

The telemetry-module change: no, and it should be dropped. It doesn't solve the bootstrap-loss problem it claims to (see the ordering issue above), it contradicts documented behavior, it's untested, and it moves the codebase closer to a stdout feedback loop.

There's also a fair question of whether the errors were being dropped at all. Because loggerProcess captures raw stderr, plain console.error output already reaches Elastic — as unstructured text, but not lost. The real gain here is queryability, not preventing data loss. Framing it as the latter led to the wrong fix.

…ry module

Replaces ad-hoc console.error calls with logError from the telemetry module
so errors are logged as a message plus a structured context object (e.g.
{ error, methodName, path, alias }) instead of string concatenation.

Coverage spans app startup (cloud connect, cron startup, background
indexes/migrations), HTTP (unhandled rejections/exceptions, method and route
handler failures), auth (OAuth providers, magic link, password reset landing,
email verification), infra (MongoDB connect, config sync, cron jobs,
Socket.IO, live-query handlers, store index creation), and related tests.

logError now normalizes Error instances into { message, stack, name } before
sending to the remote sink (Errors otherwise serialize to {}) and redacts
SENSITIVE_KEYS matches. Console output keeps raw values for local debugging.
@aadityakumarsah aadityakumarsah changed the title fix: replace console.error with structured logError from telemetry module refactor: replace console.error with structured logError from telemetry module Aug 10, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit bc0d5a9. Configure here.

During bootstrap (setMetadata -> connect -> index/migration creation ->
initMetrics) telemetry is enabled but the Winston logger does not exist yet,
so logError had no sink and startup errors (MongoDB connect failures,
unique-index violation reports) were silently dropped.

Restores the console fallback as a single shouldLogToConsole predicate so all
three log functions share it, documents the contract, and marks the safety
property (startLoggerProcess only starts after the logger exists, so the
capture loop can never re-enter this branch).
@omegascorp

Copy link
Copy Markdown
Collaborator

@aadityakumarsah could you resolve the conflicts?

@aadityakumarsah

Copy link
Copy Markdown
Contributor Author

Rn I'm out of Town

@omegascorp

Copy link
Copy Markdown
Collaborator

Closing this one. Since it was opened, #343 removed the winston/Elastic log forwarding that the telemetry changes here targeted, and error reporting has moved to captureError (#337, #365). The auth/cron/workflow changes bundled in were merged separately via #315, #279, #345, #324 and #325. The branch is now 30 commits behind with 17 conflicting files, so it's simpler to start fresh. The remaining console.error → logError call-site cleanup is still welcome as a small new PR against current main if you'd like to pick it up. Thanks for the work on this!

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