3

I am using the standard Python logging package to write logfiles in a Flask application. I would like to add the user ip address and if the user is authenticated I would also like to log the user id. Does anybody know how to do this? Right now my formatter looks like this

fmt = ('%(asctime)s - %(name)s - %(levelname)s - '
       '%(filename)s:%(lineno)s - %(funcName)20s() - %(message)s')
formatter = logging.Formatter(fmt)
carl
  • 4,216
  • 9
  • 55
  • 103

1 Answers1

5

Ok I manager to do it by adding a costum filter

class ContextualFilter(logging.Filter):
    def filter(self, log_record):
        ''' Provide some extra variables to give our logs some better info '''
        log_record.utcnow = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S,%f %Z')
        log_record.url = request.path
        log_record.method = request.method
        # Try to get the IP address of the user through reverse proxy
        log_record.ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        if current_user.is_anonymous():
            log_record.user_id = 'guest'
        else:
            log_record.user_id = current_user.get_id()
        return True

which can be added to the logger as

std_logger.addFilter(ContextualFilter())

the formatter than should be something like

    fmt = ('%(utcnow)s - %(levelname)s - '
       'user_id:%(user_id)s - ip:%(ip)s - %(method)s - %(url)s - '
       '%(filename)s:%(lineno)s - %(funcName)20s() - %(message)s')
carl
  • 4,216
  • 9
  • 55
  • 103