Skip to content

fix(logging): keep file tracebacks uncolored while stderr stays colored - #156

Open
Question86 wants to merge 1 commit into
Qix-:masterfrom
Question86:fix/issue-87-no-color-file-logs
Open

fix(logging): keep file tracebacks uncolored while stderr stays colored#156
Question86 wants to merge 1 commit into
Qix-:masterfrom
Question86:fix/issue-87-no-color-file-logs

Conversation

@Question86

Copy link
Copy Markdown

Summary

This patch fixes the ANSI color leak into file logs while keeping colored tracebacks on stderr.

What changed

  • better_exceptions/log.py
    • Patch formatters per-handler instead of mutating a shared formatter instance.
    • Apply colored traceback formatting only for StreamHandler targeting sys.stderr.
    • Apply uncolored traceback formatting for FileHandler.
    • Invalidate record.exc_text cache per formatter call so each handler can format exceptions independently.
    • Restore AssertionError.args after formatting to avoid side effects when the same exception is formatted by multiple handlers.
  • test/test_file_logging.py
    • Adds regression coverage for the real bug scenario:
      • shared formatter instance across stderr and file handlers
      • both handler orders (stderr first / file first)
    • Asserts: stderr contains ANSI, file does not.
  • test_all.sh
    • Executes test/test_file_logging.py as an assertion-style test.

Why this approach

The issue appears when multiple handlers share one formatter object and logging caches record.exc_text. Patching a formatter globally can make file handlers inherit ANSI escapes. This patch isolates formatter behavior per handler and prevents cache cross-contamination.

Closes #87

@Question86

Copy link
Copy Markdown
Author

Follow-up on design choices:\n\n- This patch intentionally handles the shared-formatter case (same Formatter instance attached to stderr + file handlers), which is where ANSI leakage commonly appears in practice.\n- It clears
ecord.exc_text per formatter call so each handler can apply its own exception rendering policy (colored stderr vs plain file output).\n- It restores AssertionError.args after formatting to avoid cross-handler side effects when the same exception is formatted more than once.\n- Added regression coverage in est/test_file_logging.py for both handler orders (stderr-first and file-first).\n\nHappy to adjust style/scope if you prefer a narrower patch.

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.

Logged exceptions shouldn't contain colour

1 participant