[Python] How to have separate logging for instances of a class

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class that does some logging, and I want to be able to easily distinguish log messages that are from different instances of the class.

    So, I thought I would create a logger object in the class __init__ method that has a unique identifier in the message formatter:

    import logging

    class Job:
    def __init__(self, jobid):
    self.logger = logging.getLogger(__name__)
    self.logger.setLevel(logging.INFO)

    handler = logging.StreamHandler()
    formatter = logging.Formatter(
    f'%(asctime)s %(levelname)-8s [{jobid}] %(message)s'
    )

    handler.setFormatter(formatter)
    self.logger.addHandler(handler)

    def logit(self, message):
    self.logger.info(message)

    j = Job(123)
    k = Job(456)

    j.logit('j starting')
    k.logit('k starting')

    j.logit('j ending')
    k.logit('k ending')


    When the code runs, I expect to see this output:

    2025-07-15 14:46:01,192 INFO [123] j starting
    2025-07-15 14:46:01,192 INFO [456] k starting
    2025-07-15 14:46:01,192 INFO [123] j ending
    2025-07-15 14:46:01,192 INFO [456] k ending


    But instead, I see this:

    2025-07-15 14:45:11,960 INFO [123] j starting
    2025-07-15 14:45:11,960 INFO [456] j starting
    2025-07-15 14:45:11,960 INFO [123] k starting
    2025-07-15 14:45:11,960 INFO [456] k starting
    2025-07-15 14:45:11,961 INFO [123] j ending
    2025-07-15 14:45:11,961 INFO [456] j ending
    2025-07-15 14:45:11,961 INFO [123] k ending
    2025-07-15 14:45:11,961 INFO [456] k ending


    All of the messages are logged twice, once with jobid 123 and again with jobid 456.

    I suppose this happens because logging.getLogger(__name__) always produces the same logger object, which then gets multiple handlers added to it.

    What is the solution here?

    Do I need to pass a unique name to getLogger(), like f'{__name__}::{jobid}', to ensure that each logger object is unique?

    Continue reading...

Compartilhe esta Página