2026, Jan 02 05:00

Log a Single Startup Line in Flask Using the Application Context and Environment Variables

Learn how to emit a single, clean startup log in Flask using the application context and .flaskenv environment variables—no per-request noise or custom parsing.

Logging where a Flask application is running sounds trivial until you want it to happen exactly once at startup and without hardcoding values. If your configuration lives in .flaskenv, the goal is to print a single, clean line when the app boots, avoid per-request noise, and skip any custom parsing.

What we start with

Configuration lives in .flaskenv and defines the module, host, and port. That’s all we need to announce the fully qualified URL at startup.

FLASK_APP=simpleflask.app
FLASK_RUN_HOST=127.0.0.1
FLASK_RUN_PORT=60210

The desired one-time message looks like this:

Running my.flask.app on http://127.0.0.1:60210 ...

Why this is a problem

The message must be emitted once, not on every request. You also don’t want to manually parse .flaskenv. The simplest path is to rely on values already available in the process environment and use Flask’s own logger inside an application context, so the logging happens in application scope rather than request scope.

Solution

Use the application context to access app-level logging and read host, port, and module from the environment. This avoids custom parsing and ensures the line is produced a single time during startup logic.

from flask import Flask
import os

svc = Flask(__name__)

# Other setup can live here

with svc.app_context():
    svc.logger.info(
        f"Running {os.environ.get('FLASK_APP')} on http://{os.environ.get('FLASK_RUN_HOST')}:{os.environ.get('FLASK_RUN_PORT')} ..."
    )

How it works

The application context makes the built-in logger available. The message is composed from environment variables that mirror the settings in .flaskenv, so there’s no need to parse the file directly. Because this code runs during application setup, it executes once and doesn’t repeat per request.

Why this matters

A single, well-placed startup log line is a practical health signal: it shows what is being served and where, without cluttering request logs. You also keep configuration as the single source of truth and avoid hand-rolled readers for .flaskenv.

Takeaways

Log startup information from the application context with the built-in logger and read values from the environment. This keeps the message accurate, avoids request-time duplication, and removes the need to parse .flaskenv by hand.