[파이썬] Flask 앱 로깅

Logging is an essential part of any Flask application as it helps developers track errors, debug issues, and analyze application behavior. The Flask framework provides built-in support for logging, making it easy to configure and customize logging in your Flask application.

In this blog post, we will explore how to set up logging in a Flask app using Python’s logging module. We will cover different logging levels, formatting log output, and organizing log files.

Setting up logging in Flask

To get started with logging in Flask, we need to import the logging module and create an instance of the Flask app.

import logging
from flask import Flask

app = Flask(__name__)

Next, we can configure the logging settings for our Flask app. Flask uses the same logging configuration as Python’s logging module.

# Set the logging level
app.logger.setLevel(logging.INFO)

# Create a file handler to write log messages to a file
file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.INFO)

# Create a formatter to define the log message format
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)

# Add the file handler to the logger
app.logger.addHandler(file_handler)

In the above code, we set the logging level to INFO, which means that log messages with a level of INFO or higher will be logged. We create a file handler to write the log messages to a file named app.log. The formatter specifies the format of the log message, including the timestamp, log level, and the actual log message. Finally, we add the file handler to the Flask app’s logger.

Logging in Flask

Once logging is set up, we can start logging messages within our Flask app. Flask provides a convenient logger object that can be accessed using app.logger.

@app.route("/")
def index():
    app.logger.info("Homepage accessed")
    return "Welcome to my Flask app"

In the above code, we log an INFO level message whenever the homepage is accessed. You can use different logging levels like DEBUG, INFO, WARNING, ERROR, and CRITICAL depending on the severity of the log message.

Log file organization

As your Flask application grows, you may want to organize your log files based on different criteria like date, log level, or module. Python’s logging module provides various ways to achieve this.

One common approach is to use the RotatingFileHandler class, which allows us to rotate log files based on size or time.

from logging.handlers import RotatingFileHandler

# Create a rotating file handler
rotating_handler = RotatingFileHandler('app.log', maxBytes=1024*1024, backupCount=5)

# Set the log level and formatter
rotating_handler.setLevel(logging.INFO)
rotating_handler.setFormatter(formatter)

# Add the rotating file handler to the logger
app.logger.addHandler(rotating_handler)

In the above code, we create a RotatingFileHandler that rotates log files when they exceed 1 MB in size. We can also specify the number of backup log files to keep. This ensures that the log files don’t grow too large and older log files are automatically deleted or archived.

Conclusion

Logging is a crucial aspect of Flask app development, providing valuable insights into the application’s behavior and helping identify and debug issues. By utilizing the logging module in Python, Flask offers a flexible and efficient way to configure and customize logging in your application.

In this blog post, we covered the basic setup for logging in a Flask app, logging at different levels, formatting log output, and organizing log files. With this knowledge, you can effectively log and monitor your Flask applications, enabling easier debugging and maintenance.

Happy Flask logging!