Skip to content

Instantly share code, notes, and snippets.

@jhorneman
Created July 26, 2012 09:18
Show Gist options
  • Save jhorneman/3181165 to your computer and use it in GitHub Desktop.
Save jhorneman/3181165 to your computer and use it in GitHub Desktop.
Some code snippets showing how one could send logging output to a web page in Python
# web_page_logger.py
import logging
class WebPageHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self)
self.messages = []
def emit(self, record):
self.messages.append(self.format(record))
def get_messages(self):
return self.messages
# Create a handler and add it to your loggers:
log_handler = WebPageHandler()
log_handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
log_handler.setFormatter(formatter)
logging.getLogger(__main__).addHandler(log_handler)
# Then, using Flask:
@app.before_request
def set_up_logging():
global log_handler
g.log_handler = log_handler
# And then in your Jinja2 template:
{% for message in g.log_handler.get_messages() %}
<p class='log'>{{ message }}</p>
{% endfor %}
# Not super pretty. There are other ways of doing this. But this works and is helpful.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment