9

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',
         },
    }
}
1

1 Answer 1

18

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())
Sign up to request clarification or add additional context in comments.

2 Comments

hi brother where to write this class
@vijinselvaraj I've added an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.