rmweiss
rmweiss

Reputation: 716

Getting username from flask session into gunicorn log

Is there a way to include a value from the flask session (like username in this case) into the access log of gunicorn?

I know that I can include custom values with a filter like this:

class UserFilter(logging.Filter):
    def filter(self, record):
        record.username = "TestUser"
        return True

But as soon as I try to get the value for record.username from the session I get:

RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.

Upvotes: 2

Views: 296

Answers (1)

León
León

Reputation: 106

I am trying to do something similar. I avoided your error by checking if there is a request context:

if has_request_context():
        return current_user.get_id() if current_user.is_authenticated else "Anonymous"
    return "System"

My implementation is with flask-login but the point is to use has_request_context():

from flask import has_request_context

Upvotes: 0

Related Questions