logging errors with flask


Question

I'm trying to log an error in a decorator function using app.logger.error(''), but it just doesn't work. In addition I cant debug this well and I can only see the response from the http client:

(I'm using nginx+uwsgi+flask)

HTTP/1.1 502 Bad Gateway

Server: nginx

Date: Sun, 12 Aug 2012 15:45:09 GMT

Content-Type: text/html

Content-Length: 14

Connection: keep-alive

Everything works great with out the line: app.logger.error('panic !!!')

def mydecorator():
    def decorator(f):
        def wrapped_function(*args, **kwargs):
            try:
                ip = Mytable.query.filter_by(ip=request.remote_addr).first()
            except:
                app.logger.error('panic !!!')
            else:
                dootherthing()

            resp = make_response(f(*args, **kwargs))
            h = resp.headers
            h['add-this-header'] = ":)"
            return resp
        return update_wrapper(wrapped_function, f)
    return decorator

It seems that it is out of context or something.

1
7
8/25/2012 1:24:17 AM

Accepted Answer

in fact, the decorator wasnt able to detect the app instance out of context, i solve this using current_app:

1st. Import the method: from flask import current_app

2nd. append any app class to current_app: current_app.logger.error('panic !!!')

info @ http://flask.pocoo.org/docs/api/#flask.current_app

"Points to the application handling the request. This is useful for extensions that want to support multiple applications running side by side. This is powered by the application context and not by the request context, so you can change the value of this proxy by using the app_context() method."

9
8/25/2012 1:06:13 AM

Is app defined anywhere in the script that you've posted?

Also, to help with debugging, when testing you should consider using the run() method with debug mode.

app.run(debug=True)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon