Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference in putting the logging statement in a module level vs in a class level?

Tags:

python

logging

module1.py

#!/usr/bin/env python
import logging
LOGGER = logging.getLogger(__main__)
class MyClass()
    def __init__(self):
        LOGGER.info('test')

Versus

module2.py

#!/usr/bin/env python
import logging
class MyClass()
    def __init__(self):
        self.LOGGER = logging.getLogger(__main__)
        self.LOGGER.info('test')

Seems to me like module2.py will give some unpredictable outcome when imported by other modules. I'm not sure though.

like image 423
lionel319 Avatar asked Feb 02 '26 16:02

lionel319


1 Answers

logging.getLogger() returns a singleton (per given name); there's no difference in storing it as a module global or as an instance attribute. Your code is referencing the same object in both cases.

Quoting the documentation:

Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.

and from the logging.getLogger() function itself:

All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.

like image 159
Martijn Pieters Avatar answered Feb 05 '26 06:02

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!