Skip to content

Instantly share code, notes, and snippets.

@bootandy
Created June 30, 2020 14:51
Show Gist options
  • Save bootandy/f8ee45cc1c276dfc684ed9d797ec9eeb to your computer and use it in GitHub Desktop.
Save bootandy/f8ee45cc1c276dfc684ed9d797ec9eeb to your computer and use it in GitHub Desktop.
flask with logging
# 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