Alvarolm
Alvarolm

Reputation: 483

logging errors with flask

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.

Upvotes: 9

Views: 14374

Answers (2)

Alvarolm
Alvarolm

Reputation: 483

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."

Upvotes: 9

Mark Hildreth
Mark Hildreth

Reputation: 43071

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)

Upvotes: 0

Related Questions