Skip to content

Instantly share code, notes, and snippets.

@anandadake
Last active December 15, 2023 07:43
Show Gist options
  • Select an option

  • Save anandadake/9249bdecde477918335bddc0ee2a091e to your computer and use it in GitHub Desktop.

Select an option

Save anandadake/9249bdecde477918335bddc0ee2a091e to your computer and use it in GitHub Desktop.
Logging in Flask Into File: Introduction and Practical Example
# -*- encoding: utf-8 -*-
"""
python -m pip install flask
Python Application
"""
import os
from flask import Flask
from datetime import datetime
from logging.config import dictConfig
LOGGING_CONFIG = {
# Always 1. Schema versioning may be added in a future release of logging
"version": 1,
# "Name of formatter" : {Formatter Config Dict}
"formatters": {
# Formatter Name
"standard": {
# class is always "logging.Formatter"
"class": "logging.Formatter",
# Optional: logging output format
"format": '[%(asctime)s] %(levelname)8s in %(module)20s::%(lineno)5s %(message)s',
# Optional: asctime format
"datefmt": "%d %b %y %H:%M:%S"
}
},
# Handlers use the formatter names declared above
"handlers": {
# Name of handler
"console": {
# The class of logger. A mixture of logging.config.dictConfig() and
# logger class-specific keyword arguments (kwargs) are passed in here.
"class": "logging.StreamHandler",
# This is the formatter name declared above
"formatter": "standard",
"level": "INFO",
# The default is stderr
"stream": "ext://sys.stdout"
},
# Same as the StreamHandler example above, but with different
# handler-specific kwargs.
"file": {
"class": "logging.handlers.RotatingFileHandler",
"formatter": "standard",
"level": "INFO",
"filename": "application-" + datetime.now().strftime("%d-%m-%Y") + ".log",
"mode": "a+",
"encoding": "utf-8",
"maxBytes": 500000,
"backupCount": 4
},
},
# Loggers use the handler names declared above
"loggers": {
# if __name__ == "__main__"
"__main__": {
# Use a list even if one handler is used
"handlers": ["console", "file"],
"level": "INFO",
"propagate": False
}
},
# Just a standalone kwarg for the root logger
"root": {
"level": "INFO",
"handlers": ["file"]
}
}
dictConfig(LOGGING_CONFIG)
app = Flask(__name__)
@app.route('/')
def auth_home():
app.logger.info('This is a INFO_LOG')
app.logger.warning('This is a WARN_LOG')
app.logger.error('This is a ERROR_LOG')
app.logger.critical('This is a CRITICAL_LOG')
return '<H1>Welcome to User Authorization Module</H1>'
if __name__ == '__main__':
host = str(os.environ.get("HOST", '0.0.0.0'))
port = int(os.environ.get("PORT", 4300))
debug = bool(os.environ.get("DEBUG", True))
app.run(host=host, port=port, debug=debug)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment