Django Logger with User info

送分小仙女□ 提交于 2020-04-16 06:20:12

问题


I'm just curious. Is it possible to put User info within the formatters info in LOGGING config in setting.py?

Right now I just put that info in the message to log but maybe there's a way to set it in formatters argument.

This is my LOGGING configuration right now:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '[%(asctime)s] %(levelname)s [%(funcName)s] %(message)s'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR + '/logs/uca_{:%d_%m_%Y}.log'.format(time.now()),
            'formatter': 'simple'
        }
    },
    'loggers': {
        'ucalog': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True
        }
    }
}

I haven't seen anything similar in django's documentation and I think it would be usefull to get records of WHO did WHAT.


回答1:


try this :

'format': '[%(asctime)s] %(levelname)s [%(funcName)s] - %(username)s: %(message)s'

logging.basicConfig(format=format)
logger.info(message, extra={'username' : request.user.username})


来源:https://stackoverflow.com/questions/49534211/django-logger-with-user-info

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!