Larry K
Larry K

Reputation: 49114

Accessing the Python flask request context for writing to Apache error log

WSGI passes its request context into Flask. How do I access it?

Eg, to write to the webserver error log from Flask app that isn't using WSGI, I write to stderr:

sys.stderr.write(str(msg) + "\n")

For this type of logging output, WSGI for Python requires that I use the WSGI request context environ['wsgi.errors'] See the WSGI debugging docs.

How do I do this?

Upvotes: 0

Views: 804

Answers (2)

Graham Dumpleton
Graham Dumpleton

Reputation: 58563

If using mod_wsgi you can just use print(). It will capture and send it to the Apache error logs. If you use a new enough mod_wsgi version and it is done inside of the context of a request, then it will even be associated with logging at Apache level for the request, which means you can tag it in Apache logs, by setting Apache log format, with Apache request ID if necessary so can associate it with any Apache logging for same request.

In general all WSGI servers will capture print() output and send it to the logs. The only exceptions tend to be for WSGI over CGI/FASTCGI/SCGI. So use of wsgi.errors is not specifically needed and it is actually rare for code to even use it.

Upvotes: 1

Larry K
Larry K

Reputation: 49114

Access the WSGI request context via request.environ

Logging to the webserver error log for both WSGI and non-WSGI configs:

def log(msg):
    out_stream = sys.stderr
    # See http://modwsgi.readthedocs.io/en/develop/user-guides/debugging-techniques.html
    if 'wsgi.errors' in request.environ: out_stream = request.environ['wsgi.errors']
    out_stream.write(str(msg) + "\n")

Upvotes: 0

Related Questions