Django logging custom attributes in formatter

后端 未结 3 839
挽巷
挽巷 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条回答
  •  一向
    一向 (楼主)
    2021-02-07 05:47

    I will provide one of many possible complete answers to this question:

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

    Other answers touched on the way to add extra contextual info through python's logging utilities. The method of using filters to attach additional information to the log record is ideal, and best described in the docs:

    https://docs.python.org/3/howto/logging-cookbook.html#using-filters-to-impart-contextual-information

    This still does not tell us how to get the user from the request in a universal way. The following library does this:

    https://github.com/ninemoreminutes/django-crum

    Thus, combine the two, and you will have a complete answer to the question that has been asked.

    import logging
    from crum import get_current_user
    
    class ContextFilter(logging.Filter):
        """
        This is a filter injects the Django user
        """
    
        def filter(self, record):
    
            record.user = get_current_user()
            return True
    
    if __name__ == '__main__':
        logging.basicConfig(level=logging.DEBUG,
                            format='User: %(user)-8s %(message)s')
        a1 = logging.getLogger('a.b.c')
    
        f = ContextFilter()
        a1.addFilter(f)
        a1.debug('A debug message')
    

    This will need to happen within a Django request-response cycle with the CRUM library properly installed.

提交回复
热议问题