Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard Django Logging

Tags:

python

django

Is it possible to wildcard a package when setting up Django logs?

Right now my LOGGING looks like:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'mypack.mod1': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'mypack.mod2': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

and my question is, is there some way to avoid needing a section for both mypack.mod1 and mypack.mod2.

like image 653
Alex Rothberg Avatar asked Feb 10 '23 10:02

Alex Rothberg


1 Answers

yes, there is a way (well several even). The simplest (and probably the best also) way is to define your logger this way:

    'mypack': {
        'handlers': ['console'],
        'level': 'DEBUG',
        'propagate': True,
    },

When in mypack.mod2 you are calling logger = logging.getLogger(__name__), name is actually mypack.mod2. Using the dotted notation if python can't find a logger for mypack.mod2, it will try for its parent (and do on if you have several layers like mypack.mod1.submod3.subsubmod42) and wil be catched by the logger named mypack.

An other way (although I wouldn't recommend it except if you really know what you are doing) is to explicitly call a specific logger by name by using logger = logging.getLogger('TheNameOfTheLoggerIWantToCall') instead of the usual call with __name__

You can also take a look at https://docs.djangoproject.com/en/1.8/topics/logging/#naming-loggers for more information.

[Updated] Under the same principle of "parental hierarchy", a logger named with an empty string would catch everything (not just Django, every log from every python module in use)

like image 168
Emma Avatar answered Feb 13 '23 03:02

Emma