Skip to content

Instantly share code, notes, and snippets.

@deangrant
Created January 3, 2023 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deangrant/3f9d14cceb4b54cd53b3ad939decb4f3 to your computer and use it in GitHub Desktop.
Save deangrant/3f9d14cceb4b54cd53b3ad939decb4f3 to your computer and use it in GitHub Desktop.
dictConfig() to create a logging configuration for Flask (https://flask.palletsprojects.com/en/1.1.x/logging/#basic-configuration)
import os
from logging.config import (
dictConfig
)
from flask import (
Flask
)
def create_app(
):
# Creates an instance of the application.
app = Flask(
__name__
)
# Loads the configuration of the application from the given object.
app.config.from_object(
f"api.config.{os.getenv('CONFIG_MODE')}Config"
)
# Configures the logging module from a dictionary.
dictConfig(
{
"version": app.config['LOG_VERSION'],
"disable_existing_loggers": app.config['LOG_DISABLE_EXISTING_LOGGERS'],
"formatters": {
"default": {
"format": app.config['LOG_FORMATTERS_DEFAULT_FORMAT'],
"datefmt": app.config['LOG_FORMATTERS_DEFAULT_DATEFMT']
}
},
"handlers": {
"wsgi": {
"class": app.config['LOG_HANDLERS_WSGI_CLASS'],
"stream": app.config['LOG_HANDLERS_WSGI_STREAM'],
"formatter": app.config['LOG_HANDLERS_WSGI_FORMATTER']
}
},
"root": {
"level": app.config['LOG_ROOT_LEVEL'],
"handlers": app.config['LOG_ROOT_LEVEL_HANDLERS']
},
}
)
# Returns the application factory.
return app
LOG_VERSION = 1
LOG_DISABLE_EXISTING_LOGGERS = True
LOG_FORMATTERS_DEFAULT_FORMAT = '[%(asctime)s] [%(levelname)s] [%(module)s]: %(message)s'
LOG_FORMATTERS_DEFAULT_DATEFMT = '%Y-%m-%d %H:%M:%S %z'
LOG_HANDLERS_WSGI_CLASS = 'logging.StreamHandler'
LOG_HANDLERS_WSGI_STREAM = 'ext://flask.logging.wsgi_errors_stream'
LOG_HANDLERS_WSGI_FORMATTER = 'default'
LOG_ROOT_LEVEL = 'INFO'
LOG_ROOT_LEVEL_HANDLERS = ['wsgi']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment