Re: [flask] Logging in production with application context
- From:
- Sean Lynch
- Date:
- 2011-11-30 @ 03:13
I think what your looking for is:
from flask import request, current_app
Then from "request" you can access remote_addr, headers, etc. For
username, you could also import "session", and get the user there, but that
is based on how you are handling your authentication (might also be
available on the "g" object if you're saving the current user to it via
@app.before_request or something).
Here is how I'm handling unhandled (500) errors on one of my sites. Note
I'm using Google Appengine, and thus using it's email APIs, but you can see
I'm logging the exception, and then emailing myself the stacktrace along
with some information about the request.
import logging
> from flask import render_template, request
> from application import app
from google.appengine.api import mail
@app.errorhandler(500)
> def server_error(e):
> logging.exception(e)
>
> import traceback, sys
> stacktrace_list = traceback.format_exception(*sys.exc_info())
> stacktrace = ''.join(stacktrace_list)
> logging.exception(stacktrace)
> # Email exception
> message = mail.EmailMessage()
> message.subject = "Uncaught Exception - %s" % stacktrace_list[-1]
> message.sender = "SOME_SENDER_EMAIL"
> message.to = "SOME_ADMIN_EMAIL"
> context = {
> 'request': request,
> 'stacktrace': stacktrace
> }
> message.body = render_template('email/exception.html', **context)
> message.send()
Then my template (email/exception.html) looks like this:
> === request.path ===
> {{ request.path }}
> === request.method ===
> {{ request.method }}
> === request.is_xhr ===
> {{ request.is_xhr }}
> === request.remote_addr ===
> {{ request.remote_addr }}
> === request.form ===
> {{ request.form|tojson|safe }}
> === request.args ===
> {{ request.args|tojson|safe }}
> === request.headers ===
> {{ request.headers }}
> === request.cookies ===
> {{ request.cookies }}
> === Stacktrace ===
> {{ stacktrace|safe}}
On Tue, Nov 29, 2011 at 7:09 PM, Jökull Sólberg Auðunsson <jokull@solberg.is
> wrote:
> I recall reading something about this from Armin at some point, but I
> can't seem to locate it now.
>
> What I want is to give formatting to my log errors that actually include
> something relevant about the current request and application context in
> question. Is this possible? Something like IP and username perhaps.
>