Skip to content

fix: prevent mutation of original dict when record.msg is a dict#66

Open
gaoflow wants to merge 1 commit into
nhairs:mainfrom
gaoflow:fix/dict-msg-mutation
Open

fix: prevent mutation of original dict when record.msg is a dict#66
gaoflow wants to merge 1 commit into
nhairs:mainfrom
gaoflow:fix/dict-msg-mutation

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 29, 2026

Copy link
Copy Markdown

Summary

When record.msg is a dict (used as a structured log message), the format() method assigns it to message_dict by reference. Subsequent mutations to message_dict -- such as injecting exc_info or stack_info -- leak into the caller's original dict, causing unexpected side effects.

Reproduction

import logging
from pythonjsonlogger import jsonlogger

logger = logging.getLogger("test")
handler = logging.StreamHandler()
handler.setFormatter(jsonlogger.JsonFormatter())
logger.addHandler(handler)

data = {"key": "value"}
try:
    1 / 0
except:
    logger.exception(data)

# data now contains "exc_info" -- the original dict was mutated!

Fix

Use record.msg.copy() instead of a direct reference, so the original dict remains untouched.

Tests

All 135 existing tests pass.

(This contribution was made under my direction and I take full responsibility for its correctness.)

When record.msg is used as a dict log message, the format() method
assigned it by reference to message_dict. Subsequent mutations to
message_dict (adding exc_info, stack_info) would leak into the caller's
original dict.

Fix by copying the dict immediately so the original is never modified.
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