flask console log
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
app.logger.debug('This is a debug message')
app.logger.info('This is an info message')
app.logger.warning('This is a warning message')
app.logger.error('This is an error message')
app.logger.critical('This is a critical message')
return 'Hello, World!'
if __name__ == '__main__':
app.run()
Explanation:
- Import Flask: Imports the Flask class from the Flask package.
- Create an instance of Flask: Initializes a Flask object named
app
. - Decorate a route: Uses the
@app.route('/')
decorator to define a route for the root URL'/'
. - Define a function for the route: Creates the
hello_world()
function that will be executed when the root URL is accessed. - Logging messages: Within the
hello_world()
function, logs different levels of messages using theapp.logger
object. Messages are logged with varying severity levels: debug, info, warning, error, and critical. - Return a response: Returns the string
'Hello, World!'
as a response when the root URL is accessed. - Run the Flask application: Checks if the script is executed directly (
if __name__ == '__main__':
) and starts the Flask web server if so.
This code creates a Flask web application with a route for the root URL and demonstrates logging different types of messages using Flask's built-in logger.