[Flask uses log function]

Configure logging in Flask

In a Flask application, logginglogging can be configured using Python's standard modules. Here's a simple example where logging is output to a file and to the console:

import logging
from logging.handlers import RotatingFileHandler
from flask import Flask

app = Flask(__name__)

# 配置日志记录
handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=1)
handler.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
handler.setFormatter(formatter)

app.logger.addHandler(handler)

if not app.debug:
    # 如果不处于调试模式,将日志输出到 stdout
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.INFO)
    app.logger.addHandler(stream_handler)

In this example, a rotated file processor called is created app.logand bound to the Flask application's logger. If not in debug mode, a stream processor is also created and bound to the logger to output logging to the console.

To log in your application, you can use a logger object, for example:

@app.route('/')
def index():
    app.logger.info('Processing request for index page')
    return 'Hello, world!'

In this example, info()the method is used to log an INFO level log indicating that a request for the home page is being processed.

It should be noted that configuring logging is a highly customizable process, you can add or remove handlers, filters, etc. according to your needs. This example only provides a simple starting point to get started with custom configurations.

Use logging in other pages of the Flask application

Using logging in other pages of the Flask application, you can log information by getting the log object of the current application. The log object can be obtained using the following code:

import log object

import logging

logger = logging.getLogger(__name__)

This code will create a __name__Logger object named , which will be the same as the name of the current module. You can then use that Logger object to log messages, for example:

record log

from flask import render_template
from app import logger

@app.route('/about')
def about():
    logger.info('Rendering about page')
    return render_template('about.html')

In this example, when the route processes the /about path, an info level log is logged and the about.html template is rendered.

It should be noted that unlike the aforementioned logger for the Flask application, the logger created here is only used for logging of the current module or blueprint. If you want to share logging configuration and handlers across your application, you should use the aforementioned application logger.

The logger in the app is used in the module

If you have a created and configured appobject and want to use the same logger in another module, you can use current_appthe method provided by Flask to get the application instance, and then get the logger object of the application. Here is a simple example:

Define the logger in the app

# app.py
import logging
from flask import Flask

app = Flask(__name__)

# 配置日志记录
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

app.logger.addHandler(handler)

appIn this example, a Flask application called is created and a logger that outputs to standard output is added to its logger object.

Using loggers in modules

# my_module.py
import logging
from flask import current_app

logger = logging.getLogger(__name__)

def do_something():
    # 获取当前应用程序的记录器对象
    app_logger = current_app.logger
    
    logger.info('Starting to do something...')
    
    # 进行一些操作
    app_logger.info('Doing something now...')
    
    logger.info('Finished doing something.')

In this example, we create another module my_module.pythat contains a do_something()function. This function will first obtain loggerthe application's logger object by obtaining the object of the current application. Then, use the object to record information before and after some operation logger, while using the application's loggerobject to record information during the operation.

Note that to use current_appmethods, you must be operating within the Flask application context. In other words, you need to make sure that the method is called in the request context or application context.

The above content uses chatgpt-based applications to play AI-assisted writing

Let's play AI>>>

Guess you like

Origin blog.csdn.net/all_night_in/article/details/130778768