Django logging custom attributes in formatter

后端 未结 3 868
挽巷
挽巷 2021-02-07 05:37

How can Django use logging to log using custom attributes in the formatter? I\'m thinking of logging the logged in username for example.

In the settings.py

3条回答
  •  旧时难觅i
    2021-02-07 05:57

    The extra keyword is not a workaround. That's the most eloquent way of writing customized formatters, unless you are writing a custom logging altogether.

    format: '%(asctime).19s %(levelname)s - %(username)s: %(message)s'
    logging.basicConfig(format=format)
    logger.info(message, extra={'username' : request.user.username})
    

    Some note from the documentation (**kwars for Django logger):

    The keys in the dictionary passed in extra should not clash with the keys used by the logging system.

    If the strings expected by the Formatter are missing, the message will not be logged.

    This feature is intended for use in specialized circumstances, and not always.

提交回复
热议问题