2

I'm new to Django and I've been assign to do a task about loggers. I have in mind a simple logger where INFO messages use a simple format and WARNING messages (and above) use a more complex one. This was my attempt:

    LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '{levelname} {message}',
            'style': '{',
        },
        'verbose': {
            'format': '{levelname}: {message} Time: [{asctime}] Module: [{module}] Process: [{process:d}] Thread: [{thread:d}] ',
            'style': '{',
        }
    },
    'handlers': {
        'console_simple': {
            'class': 'logging.StreamHandler',
            'formatter': 'simple',
            'level': 'INFO'
        },
        'console_verbose': {
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
            'level': 'WARNING'
        }
    },
    'loggers':{
        '': {
            'handlers': ['console_simple'],
            'level': 'INFO'
        }
    }
}

As you can problably imagine, the problem is that WARNING messages or higher will be logged twice. I've though about using filters, but I couldn't find any undestandable explanation on the documentation.

I've found the filter below on this thread:

import logging

class InfoFilter(logging.Filter):
    def filter(self, record):
        return record.level == logging.INFO

The problem is that I don't know how to properly use it. I've never used filters before.

The Django logging documentation has the following example:


    'filters': {
        'special': {
            '()': 'project.logging.SpecialFilter',
            'foo': 'bar',
        },
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },

Where they say that:

Defines two filters: project.logging.SpecialFilter, using the alias special. If this filter required additional arguments, they can be provided as additional keys in the filter configuration dictionary. In this case, the argument foo will be given a value of bar when instantiating SpecialFilter.

So, I believe that I need to give a value to logging.Filter the same way was "foo" received a value of "bar". The problem is that I have no idea on how to do that.

Am I at least on the right path? How can I use this filter? There are any other solutions?

1 Answers1

0

check out this

you need to put a list in the filters indicating which levels they apply to.

Samoht
  • 37
  • 6
  • Try to avoid a pure link answer, the link can expire – PV8 Oct 22 '21 at 10:48
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30147534) – Karl Oct 22 '21 at 11:27