Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging - default value to extra parameters

I would like to set default value to extra parameter user_id. I've written filter:

class SystemLogFilter(logging.Filter):
    def filter(self, record):
        if not record.user_id:
            record.user_id = '--'

        return True

But I've got this error: AttributeError: 'LogRecord' object has no attribute 'user_id'

How can I get access to user_id parameter?

This is my logging configuration:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'system_log': {
            'format': '%(asctime)-15s - %(levelname)s - %(message)s - %(user_id)s'
        },
    },
    'filters': {
        'system2': {
            '()': 'system.logging2.SystemLogFilter',
        }
    },
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': (os.path.join(BASE_DIR, 'logs/system.log')),
            'formatter': 'system_log',
            'filters': ['system2'],
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'propagate': True,
            'level': 'INFO',
         },
    }
}
like image 679
torm Avatar asked Dec 27 '14 12:12

torm


People also ask

What is Qualname in Python logging?

The qualname entry is the hierarchical channel name of the logger, that is to say the name used by the application to get the logger.

What is the default logging level in Python?

The default level is WARNING , which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise. Events that are tracked can be handled in different ways. The simplest way of handling tracked events is to print them to the console.

How do I create a multiple logging level in Python?

You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest". In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. So the file has DEBUG entries and the stream outputs only INFO.


1 Answers

You can use hasattr (a built-in function) to check whether the log record has the desired attribute. If not, then you can set a default value.

For example:

class SystemLogFilter(logging.Filter):
    def filter(self, record):
        if not hasattr(record, 'user_id'):
            record.user_id = '--'
        return True

and then you need to attach this new filter to some logger (for example root logger) somewhere in your application (preferably the start):

root_logger = logging.getLogger()
root_logger.addFilter(SystemLogFilter())
like image 118
Simeon Visser Avatar answered Oct 26 '22 20:10

Simeon Visser