68π
I typically donβt use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:
import logging
LOG = logging.getLogger(__name__)
At the top of the module and subsequent:
LOG.info('Spam and eggs are tasty!')
from anywhere in the file typically gets me to where I want to be. This avoids the need for self.log
all over the place, which tends to bother me from both a put-it-in-every-class perspective and makes me 5 characters closer to 79 character lines that fit.
You could always use a pseudo-class-decorator:
>>> import logging
>>> class Foo(object):
... def __init__(self):
... self.log.info('Meh')
...
>>> def logged_class(cls):
... cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))
...
>>> logged_class(Foo)
>>> logging.basicConfig(level=logging.DEBUG)
>>> f = Foo()
INFO:__main__.Foo:Meh
3π
For class level logging, as an alternative to a pseudo-class decorator, you could use a metaclass to make the logger for you at class creation timeβ¦
import logging
class Foo(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
type.__init__(name, bases, attrs)
cls.log = logging.getLogger('%s.%s' % (attrs['__module__'], name))
def __init__(self):
self.log.info('here I am, a %s!' % type(self).__name__)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
foo = Foo()
- [Django]-How to tell if a task has already been queued in django-celery?
- [Django]-The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS
- [Django]-How to loop over form field choices and display associated model instance fields
2π
That looks like it will work, except that self
wonβt have a __module__
attribute; its class will. The class-level logger call should look like:
self.log = logging.getLogger( "%s.%s" % ( self.__class__.__module__, self.__class__.__name__ ) )
- [Django]-How do I force Django to ignore any caches and reload data?
- [Django]-Cannot import name _uuid_generate_random in heroku django
- [Django]-Selecting specific fields using select_related in Django