SoFunction
Updated on 2024-12-10

Flask learning notes of the logging operation configuration example to explain

introductory

Previously in Django notes in detail about the logging module on formatters, handlers, loggers and other basic introduction, here will not do more introduction, details can be directly jump to view the corresponding article:Django notes thirty of the log logging details

Here is a straightforward description of how to configure log messages in Flask.

The code for this note has all been committed to github and can be accessed using the actions below:

git clone /x1204604036/flask_backend.git

1、Log Configuration

First, we create some file address variables for the log output in theconfig/ in the test environment variable file or the production environment variable file, depending on the environment, I'm here in the in which it reads as follows:

LOGGING_PATH = "e:/code/log_file/flask_backend/"
LOGGING_ERROR_PATH = "e:/code/log_file/flask_backend/flask_error.log"

followapp/config/ Create a file in the folderlogging_config.pyThe content is as follows:

# app/config/logging_config.py
from  import config
LoggingConfig = {
    "version": 1,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(filename)s %(lineno)s %(message)s",
        }
    },
    "handlers": {
        "file": {
            "level": "INFO",
            "filename": config.LOGGING_PATH,
            "formatter": "verbose",
            "class": "",
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 20,
        },
        "error_handler": {
            "level": "INFO",
            "filename": config.LOGGING_ERROR_PATH,
            "formatter": "verbose",
            "class": "",
            'maxBytes': 5 * 1024 * 1024,
            'backupCount': 20,
        },
        "email_handler": {
            "level": "WARNING",
            "class": "",
            "mailhost": ("smtp.", 25),
            "fromaddr": "hunterxxxxx@",
            "toaddrs": "120xxxx@",
            "subject": "System error",
            "credentials": ("hunterxxxx@", "JBDMVIxxxxx"),
            "timeout": 20,
        },
    },
    "root": {
        "handlers": ["file"],
        "level": "INFO",
        "propagate": True,
    },
    "loggers": {
        "error_log": {
            "handlers": ["error_handler", "email_handler"],
            "level": "INFO",
        }
    }
}

Three handlers are created here, two FileHandlers to store the logs as files, and one to send emails.

Under it, root means it is used to record the output of all Flask messages, and other loggers are recorded under loggers, where a logger that records an error corresponds to two handlers, one that logs to a file and one that sends an email.

existapp/__init__.py The logging configuration is introduced in the

# app/__init__.py
import 
from  import looging_config
def create_app():
    app = Flask(__name__)
    (looging_config.LoggingConfig)
    return app

2, log printing example

Here, let's take the exception handling in the previous section as an example of logging, and put all the code for logging output into the exception handling.exception_handler.py The content is as follows:

from  import HTTPException
from flask import jsonify, request
import logging
import traceback
logger = ("error_log")
ERROR_HTTP_CODE = 417
class UserException(Exception):
    def __init__(self, code=-1, msg="error", http_code=417):
         = code
         = msg
        self.http_code = http_code
def init_error_exception(app):
    @(HTTPException)
    def handler_http_exception(exception):
        trace_info = traceback.format_exc()
        log_msg = "request path: %s, traceback info: %s, description: %s" % (
            , trace_info, 
        )
        (log_msg)
        return jsonify({"code": -1, "msg": }), 
    @(Exception)
    def server_exception(exception):
        ("request_path: " + )
        trace_info = traceback.format_exc()
        log_msg = "request path: %s, traceback info: %s" % (, trace_info)
        (log_msg)
        ("System error message: %s" % log_msg)
        return jsonify({"code": -1, "msg": "Internal error."}), ERROR_HTTP_CODE
    @(UserException)
    def user_exception(exception):
        trace_info = traceback.format_exc()
        log_msg = "request path: %s, traceback info: %s, exception msg: %s" % (
            , trace_info, 
        )
        (log_msg)
        return jsonify({"code": , "msg": }), exception.http_code

Here, we put the request path, error message, etc. into log_msg and output it via (). In addition, here we also try to send an email to the specified mailbox for the handling of system exceptions.

take note of: Remember to change the email information in the log configuration to your actual one, I've blurred mine here.

After re-running the system and trying to trigger these three types of errors, you can see the output of the error messages in the corresponding log files. The second exception exception handling that triggered an error will also send an email.

The above is Flask Learning Notes of the logging operation example explains the details, more information about Flask logging operation configuration please pay attention to my other related articles!