Skip to content

Instantly share code, notes, and snippets.

@hibellm
Forked from jhorneman/Logging to a web page
Created October 24, 2017 19:34
Show Gist options
  • Save hibellm/b9938d04b5cbeec4abf6c48bb412ba5c to your computer and use it in GitHub Desktop.
Save hibellm/b9938d04b5cbeec4abf6c48bb412ba5c 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