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',
},
}
}
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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With