Skip to content

Fix LevelFormatter KeyError on unlisted or custom log levels#141

Open
ArmaanjeetSandhu wants to merge 1 commit into
borntyping:mainfrom
ArmaanjeetSandhu:fix/level-formatter-unlisted-level-fallback
Open

Fix LevelFormatter KeyError on unlisted or custom log levels#141
ArmaanjeetSandhu wants to merge 1 commit into
borntyping:mainfrom
ArmaanjeetSandhu:fix/level-formatter-unlisted-level-fallback

Conversation

@ArmaanjeetSandhu

Copy link
Copy Markdown

LevelFormatter.format() looked up self.formatters[record.levelname] with no fallback, so any record whose level name wasn't an exact key in fmt raised KeyError at log time. This breaks two common cases:

  • Custom levels (e.g. the TRACE level shown in docs/custom_level.py).
  • Partially-specified fmt dicts, where you only want to override some levels. Every unlisted level then crashes the logging call.

Changes

  • LevelFormatter now resolves the formatter with self.formatters.get(record.levelname, self.default_formatter).
  • The fallback resolves in this order:
    1. an explicit "DEFAULT" entry in fmt, if provided
    2. otherwise a ColoredFormatter using the default format for the chosen style, inheriting the same **kwargs.
  • Updated the LevelFormatter docstring to document the fallback and the "DEFAULT" key.
  • Added tests: test_unlisted_level_uses_default (reproduces the original KeyError) and test_explicit_default_key.

I chose a lenient fallback (format the record) over a stricter approach (re-raise with a clearer message), since silently crashing the logging path is the worse outcome and it matches how logging itself tolerates unexpected levels. Happy to switch to a descriptive error instead if strictness is preferred.

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.

1 participant