Skip to content

LoggerAdapter and %(funcName)s prints the wrong function name #115233

Description

@dogbertai

Bug report

Bug description:

Using the StyleAdapter from the Cookbook https://docs.python.org/3/howto/logging-cookbook.html
With the %(funcName)s formatter
Yields the wrong funcName in 3.11 and later.

No matter where you use the StyleAdapter logger, it always prints "log"

#!/usr/bin/env python3
import logging.handlers
import sys


class Message:
    def __init__(self, fmt, args):
        self.fmt = fmt
        self.args = args

    def __str__(self):
        return self.fmt.format(*self.args)


class StyleAdapter(logging.LoggerAdapter):
    def __init__(self, logger, extra=None):
        super().__init__(logger, extra or {})

    def log(self, level, msg, /, *args, **kwargs):
        if self.isEnabledFor(level):
            msg, kwargs = self.process(msg, kwargs)
            self.logger._log(level, Message(msg, args), (), **kwargs)


logger = StyleAdapter(logging.getLogger(__name__))


def main():
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter(
        '%(asctime)s %(name)s %(funcName)s %(levelname)s %(message)s')

    # create console handler and set level to debug
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)
    root_logger.info('Logger initialized.')

    logger.info('test')


if __name__ == '__main__':
    sys.exit(main())
PS > py -3.10 test_log.py
2024-02-09 23:15:33,506 root main INFO Logger initialized.
2024-02-09 23:15:33,506 __main__ main INFO test
PS > py -3.12 test_log.py                                                          
2024-02-09 23:15:29,298 root main INFO Logger initialized.
2024-02-09 23:15:29,299 __main__ log INFO test

CPython versions tested on:

3.10, 3.12

Operating systems tested on:

Windows

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.11only security fixes3.12only security fixes3.13bugs and security fixestype-bugAn unexpected behavior, bug, or error

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions