Created
June 30, 2020 14:51
-
-
Save bootandy/f8ee45cc1c276dfc684ed9d797ec9eeb to your computer and use it in GitHub Desktop.
flask with logging
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
# https://rz0r.net/post/2019-05-27-flask-logging/ | |
import os | |
import logging | |
import socket | |
from flask import Flask | |
from logging.config import dictConfig | |
class ContextFilter(logging.Filter): | |
hostname = socket.gethostname() | |
def filter(self, record): | |
record.hostname = ContextFilter.hostname | |
return True | |
logging_configuration = dict( | |
version=1, | |
disable_existing_loggers=False, | |
formatters={ | |
"default": {"format": "[%(hostname)s %(asctime)s] %(levelname)s in %(module)s: %(message)s"}, | |
}, | |
filters={"hostname_filter": {"()": ContextFilter}}, | |
handlers={ | |
"console": { | |
"class": "logging.StreamHandler", | |
"formatter": "default", | |
"filters": ["hostname_filter"], | |
} | |
}, | |
root={"handlers": ["console"], "level": os.getenv("LOG_LEVEL", "INFO")}, | |
) | |
dictConfig(logging_configuration) | |
app = Flask(__name__) | |
logger = logging.getLogger(__name__) | |
@app.route("/") | |
def home(): | |
logger.debug("debug message") | |
logger.info("info message") | |
logger.warning("warning message") | |
logger.error("error message") | |
logger.critical("critical error message") | |
return "Hello World" | |
if __name__ == "__main__": | |
app.run() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment