Created
July 26, 2012 09:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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