### Install Microbootstrap with FastAPI Extra Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Install microbootstrap with the 'fastapi' extra using uv, poetry, or pip. ```bash uv add "microbootstrap[fastapi]" ``` ```bash poetry add microbootstrap -E fastapi ``` ```bash pip install "microbootstrap[fastapi]" ``` -------------------------------- ### Using InstrumentsSetupper with Setup and Teardown Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Manually manage the setup and teardown of instruments in your project using InstrumentsSetupper's setup() and teardown() methods. This provides more control over the instrument lifecycle. ```python current_setupper = InstrumentsSetupper(YourSettings()) current_setupper.setup() try: while True: print("doing something useful") time.sleep(1) finally: current_setupper.teardown() ``` -------------------------------- ### Install Dependencies with Just Source: https://github.com/community-of-python/microbootstrap/blob/main/CLAUDE.md Installs all project dependencies using the 'just' command. This command performs dependency locking and synchronization. ```bash just install # Install all deps (uv lock --upgrade + uv sync --all-extras) ``` -------------------------------- ### Setup Instruments Without Web Framework Source: https://context7.com/community-of-python/microbootstrap/llms.txt Use InstrumentsSetupper for framework-agnostic services like background workers or CLI tools to set up Logging, Sentry, OpenTelemetry, and Pyroscope. Supports context manager and explicit setup/teardown. ```python import time from microbootstrap import InstrumentsSetupperSettings from microbootstrap.instruments_setupper import InstrumentsSetupper class Settings(InstrumentsSetupperSettings): service_name: str = "data-pipeline" service_debug: bool = False sentry_dsn: str = "https://key@sentry.io/333" opentelemetry_endpoint: str = "http://otel-collector:4317" settings = Settings() # Context manager usage — setup on enter, teardown on exit with InstrumentsSetupper(settings): while True: print("Processing data...") time.sleep(5) # Explicit setup/teardown setupper = InstrumentsSetupper(settings) setupper.setup() try: for item in range(100): process(item) finally: setupper.teardown() # Override instrument config before setup from microbootstrap import SentryConfig, OpentelemetryConfig setupper = ( InstrumentsSetupper(settings) .configure_instrument(SentryConfig(sentry_sample_rate=0.5)) .configure_instrument(OpentelemetryConfig(opentelemetry_log_traces=True)) ) setupper.setup() ``` -------------------------------- ### Configure FastStream Prometheus Middleware Source: https://context7.com/community-of-python/microbootstrap/llms.txt Configure Prometheus metrics for FastStream by setting the metrics path and specifying the Prometheus middleware class. This example uses RedisPrometheusMiddleware. ```python from microbootstrap import FastApiSettings, LitestarSettings, FastStreamSettings from microbootstrap import FastApiPrometheusConfig, LitestarPrometheusConfig, FastStreamPrometheusConfig from microbootstrap.bootstrappers.fastapi import FastApiBootstrapper from microbootstrap.bootstrappers.litestar import LitestarBootstrapper # FastStream from faststream.redis.prometheus import RedisPrometheusMiddleware class WorkerSettings(FastStreamSettings): prometheus_metrics_path: str = "/metrics" prometheus_middleware_cls = RedisPrometheusMiddleware ``` -------------------------------- ### Configure Health Checks in Litestar Source: https://context7.com/community-of-python/microbootstrap/llms.txt Enables a /health/ GET route that returns service status. Activates when health_checks_enabled is True. To disable, configure HealthChecksConfig with health_checks_enabled=False. ```python from microbootstrap import LitestarSettings, HealthChecksConfig from microbootstrap.bootstrappers.litestar import LitestarBootstrapper class Settings(LitestarSettings): service_name: str = "inventory-service" service_version: str = "1.1.0" health_checks_enabled: bool = True health_checks_path: str = "/health/" health_checks_include_in_schema: bool = False # hide from OpenAPI schema settings = Settings() app = LitestarBootstrapper(settings).bootstrap() # GET /health/ response: # {"service_name": "inventory-service", "service_version": "1.1.0", "health_status": true} # To disable health checks: app = ( LitestarBootstrapper(settings) .configure_instrument(HealthChecksConfig(health_checks_enabled=False)) .bootstrap() ) ``` -------------------------------- ### Bootstrap FastAPI Application Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Create a FastAPI application with pre-configured instruments using FastApiBootstrapper. ```python import fastapi from microbootstrap import FastApiSettings from microbootstrap.bootstrappers.fastapi import FastApiBootstrapper class YourSettings(FastApiSettings): # General settings service_debug: bool = False service_name: str = "my-awesome-service" # Sentry settings sentry_dsn: str = "your-sentry-dsn" # Prometheus settings prometheus_metrics_path: str = "/my-path" # Opentelemetry settings opentelemetry_container_name: str = "your-container" opentelemetry_endpoint: str = "/opentelemetry-endpoint" settings = YourSettings() application: fastapi.FastAPI = FastApiBootstrapper(settings).bootstrap() ``` -------------------------------- ### Create Granian ASGI Server Instance Source: https://context7.com/community-of-python/microbootstrap/llms.txt Creates a granian.Granian server configured from settings. Reads server host, port, workers, reload status, and log level from settings. Requires the 'granian' extra. The 'factory=True' argument tells Granian to call the provided app factory function. ```python from microbootstrap import LitestarSettings from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap.granian_server import create_granian_server import litestar class Settings(LitestarSettings): server_host: str = "0.0.0.0" server_port: int = 8000 server_workers_count: int = 2 server_reload: bool = False settings = Settings() @litestar.get("/") async def index() -> dict: return {"status": "ok"} def create_app() -> litestar.Litestar: from microbootstrap.config.litestar import LitestarConfig return LitestarBootstrapper(settings).configure_application( LitestarConfig(route_handlers=[index]) ).bootstrap() if __name__ == "__main__": # factory=True means Granian calls create_app() to get the app create_granian_server( "mymodule:create_app", settings, factory=True, ).serve() # Equivalent direct serve (non-factory): # app = create_app() # create_granian_server("mymodule:app", settings).serve() ``` -------------------------------- ### Configure Swagger/OpenAPI Documentation Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Extend BaseServiceSettings to configure Swagger UI and OpenAPI documentation. Set service name, description, version, static path, and Swagger path. ```python from microbootstrap.settings import BaseServiceSettings class YourSettings(BaseServiceSettings): service_name: str = "micro-service" service_description: str = "Micro service description" service_version: str = "1.0.0" service_static_path: str = "/static" swagger_path: str = "/docs" swagger_offline_docs: bool = False swagger_extra_params: dict[str, Any] = {} ``` -------------------------------- ### Configure Multiple Instruments with LitestarBootstrapper Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure multiple instruments simultaneously using the configure_instruments method. This approach is efficient for setting up several integrations at once. ```python import litestar from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap import SentryConfig, OpentelemetryConfig application: litestar.Litestar = ( LitestarBootstrapper(settings) .configure_instruments( SentryConfig(sentry_dsn="https://examplePublicKey@o0.ingest.sentry.io/0"), OpentelemetryConfig(opentelemetry_endpoint="/new-endpoint") ) .bootstrap() ) ``` -------------------------------- ### Run Full Test Suite with Just Source: https://github.com/community-of-python/microbootstrap/blob/main/CLAUDE.md Executes the complete test suite for the project, including coverage reporting. ```bash just test # Run full test suite with coverage ``` -------------------------------- ### Configure Multiple Litestar Instruments at Once Source: https://context7.com/community-of-python/microbootstrap/llms.txt Configure multiple instruments simultaneously using `configure_instruments`. ```python from microbootstrap import CorsConfig app = ( LitestarBootstrapper(settings) .configure_instruments( SentryConfig(sentry_tags={"release": "1.4.0"}), CorsConfig(cors_allowed_origins=["https://admin.example.com"]), ) .configure_application(LitestarConfig(route_handlers=[get_order])) .bootstrap() ) ``` -------------------------------- ### FastStream Bootstrapper Configuration Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure FastStream application with custom settings including Sentry, Prometheus, and OpenTelemetry. Settings can be sourced from environment variables. ```python from faststream.asgi import AsgiFastStream from microbootstrap import FastStreamSettings from microbootstrap.bootstrappers.faststream import FastStreamBootstrapper class YourSettings(FastStreamSettings): # General settings service_debug: bool = False service_name: str = "my-awesome-service" # Sentry settings sentry_dsn: str = "your-sentry-dsn" # Prometheus settings prometheus_metrics_path: str = "/my-path" # Opentelemetry settings opentelemetry_container_name: str = "your-container" opentelemetry_endpoint: str = "/opentelemetry-endpoint" settings = YourSettings() application: AsgiFastStream = FastStreamBootstrapper(settings).bootstrap() ``` -------------------------------- ### Bootstrap a FastAPI Application with Default Instruments Source: https://context7.com/community-of-python/microbootstrap/llms.txt Bootstrap a FastAPI application with default instruments including Sentry, OpenTelemetry, Prometheus, structlog logging, CORS, Swagger docs, and health check router. The lifespan is managed automatically. ```python import fastapi from microbootstrap import FastApiSettings from microbootstrap.bootstrappers.fastapi import FastApiBootstrapper from microbootstrap.config.fastapi import FastApiConfig from microbootstrap import SentryConfig, FastApiPrometheusConfig class Settings(FastApiSettings): service_name: str = "user-service" service_version: str = "3.0.0" service_debug: bool = False sentry_dsn: str = "https://key@sentry.io/111" opentelemetry_endpoint: str = "http://otel-collector:4317" prometheus_metrics_path: str = "/metrics" cors_allowed_origins: list[str] = ["*"] swagger_offline_docs: bool = True # serves Swagger JS/CSS from /static settings = Settings() def create_app() -> fastapi.FastAPI: app = FastApiBootstrapper(settings).bootstrap() @app.get("/users/{user_id}") async def get_user(user_id: int) -> dict: return {"user_id": user_id, "name": "Alice"} @app.post("/users") async def create_user(payload: dict) -> dict: return {"user_id": 1, **payload} return app ``` -------------------------------- ### Bootstrap FastStream ASGI App with Instruments Source: https://context7.com/community-of-python/microbootstrap/llms.txt Use FastStreamBootstrapper to create an AsgiFastStream application with Sentry, Pyroscope, OpenTelemetry, structured logging, Prometheus, and health check routes. The broker must be configured via FastStreamConfig. ```python from faststream.redis import RedisBroker from faststream.redis.opentelemetry import RedisTelemetryMiddleware from faststream.redis.prometheus import RedisPrometheusMiddleware from faststream.asgi import AsgiFastStream from microbootstrap import FastStreamSettings from microbootstrap.bootstrappers.faststream import FastStreamBootstrapper from microbootstrap.config.faststream import FastStreamConfig class Settings(FastStreamSettings): service_name: str = "notification-worker" service_debug: bool = False sentry_dsn: str = "https://key@sentry.io/222" opentelemetry_endpoint: str = "http://otel-collector:4317" opentelemetry_middleware_cls = RedisTelemetryMiddleware prometheus_metrics_path: str = "/metrics" prometheus_middleware_cls = RedisPrometheusMiddleware asyncapi_path: str | None = "/asyncapi" # set None to disable AsyncAPI docs settings = Settings() def create_app() -> AsgiFastStream: broker = RedisBroker("redis://localhost:6379") @broker.subscriber("orders.created") @broker.publisher("notifications.send") async def handle_order_created(order_id: int) -> dict: return {"recipient": "user@example.com", "message": f"Order {order_id} confirmed"} @broker.subscriber("notifications.send") async def send_notification(payload: dict) -> None: print(f"Sending notification: {payload}") app: AsgiFastStream = ( FastStreamBootstrapper(settings) .configure_application(FastStreamConfig(broker=broker)) .bootstrap() ) @app.after_startup async def publish_test_event() -> None: await broker.connect() await broker.publish(1001, "orders.created") return app if __name__ == "__main__": from microbootstrap.granian_server import create_granian_server create_granian_server("myworker:create_app", settings, factory=True).serve() ``` -------------------------------- ### Bootstrap Litestar Application Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Create a Litestar application with pre-configured instruments using LitestarBootstrapper. ```python import litestar from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from your_application.settings import settings # Use the Litestar application! application: litestar.Litestar = LitestarBootstrapper(settings).bootstrap() ``` -------------------------------- ### Configure FastStream AsyncAPI Path Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Extend FastStreamSettings to customize the path for AsyncAPI documentation. By default, it is available under the '/asyncapi' route. ```python from microbootstrap import FastStreamSettings class YourSettings(FastStreamSettings): asyncapi_path: str | None = None ``` -------------------------------- ### Custom Settings with Environment Variables Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Define custom settings by inheriting from BaseServiceSettings and add your own parameters. These parameters can be sourced from environment variables, optionally with a prefix. ```python class YourSettings(BaseServiceSettings): service_debug: bool = True service_name: str = "micro-service" your_awesome_parameter: str = "really awesome" ... # Other settings here ``` -------------------------------- ### Configure Instruments with LitestarBootstrapper Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Manually configure instruments like Sentry and Opentelemetry using their respective configuration classes and the configure_instrument method. This is useful when settings are not sufficient. ```python import litestar from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap import SentryConfig, OpentelemetryConfig application: litestar.Litestar = ( LitestarBootstrapper(settings) .configure_instrument(SentryConfig(sentry_dsn="https://new-dsn")) .configure_instrument(OpentelemetryConfig(opentelemetry_endpoint="/new-endpoint")) .bootstrap() ) ``` -------------------------------- ### Using InstrumentsSetupper as a Context Manager Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Integrate Sentry, OpenTelemetry, Pyroscope, and Logging instruments into non-framework projects using InstrumentsSetupper as a context manager. Ensure necessary settings are defined. ```python from microbootstrap.instruments_setupper import InstrumentsSetupper from microbootstrap import InstrumentsSetupperSettings class YourSettings(InstrumentsSetupperSettings): ... with InstrumentsSetupper(YourSettings()): while True: print("doing something useful") time.sleep(1) ``` -------------------------------- ### Bootstrapping Litestar with Custom Instrument Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure your custom instrument by including its configuration parameters directly in your LitestarSettings class. This simplifies the bootstrapping process by consolidating settings. ```python from microbootstrap import LitestarSettings from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from your_app import MyInstrumentConfig class YourSettings(LitestarSettings, MyInstrumentConfig): your_string_parameter: str = "very-nice-parameter" your_list_parameter: list = ["very-special-list"] settings = YourSettings() application: litestar.Litestar = LitestarBootstrapper(settings).bootstrap() ``` -------------------------------- ### Bootstrapping Litestar with a Custom Instrument Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Bootstrap a Litestar application with your custom instrument by configuring it via configure_instrument() before calling bootstrap(). Ensure your custom instrument's configuration parameters are provided. ```python import litestar from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap import SentryConfig, OpentelemetryConfig from your_app import MyInstrumentConfig application: litestar.Litestar = ( LitestarBootstrapper(settings) .configure_instrument( MyInstrumentConfig( your_string_parameter="very-nice-parameter", your_list_parameter=["very-special-list"], ) ) .bootstrap() ) ``` -------------------------------- ### Bootstrap Litestar App with Microbootstrap Source: https://context7.com/community-of-python/microbootstrap/llms.txt Bootstrap a Litestar application with integrated observability and infrastructure instruments using LitestarBootstrapper. Configure application routes and bootstrap the app instance. ```python import litestar from microbootstrap import LitestarSettings from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap.config.litestar import LitestarConfig from microbootstrap import SentryConfig, OpentelemetryConfig class Settings(LitestarSettings): service_name: str = "order-service" service_version: str = "1.4.0" service_debug: bool = False sentry_dsn: str = "https://key@sentry.io/456" opentelemetry_endpoint: str = "http://otel-collector:4317" prometheus_metrics_path: str = "/metrics" cors_allowed_origins: list[str] = ["https://frontend.example.com"] settings = Settings() @litestar.get("/orders/{order_id:int}") async def get_order(order_id: int) -> dict: return {"order_id": order_id, "status": "shipped"} @litestar.post("/orders") async def create_order(data: dict) -> dict: return {"order_id": 42, "status": "created"} # Basic bootstrap app: litestar.Litestar = ( LitestarBootstrapper(settings) .configure_application(LitestarConfig(route_handlers=[get_order, create_order])) .bootstrap() ) ``` -------------------------------- ### Run Specific Test File with Just Source: https://github.com/community-of-python/microbootstrap/blob/main/CLAUDE.md Runs tests from a single specified test file. ```bash just test tests/path/to/test_file.py # Run single test file ``` -------------------------------- ### Run FastAPI Application with Granian Server Source: https://context7.com/community-of-python/microbootstrap/llms.txt Run a FastAPI application using the Granian server, specifying the app factory and settings. ```python if __name__ == "__main__": from microbootstrap.granian_server import create_granian_server create_granian_server("myapp:create_app", settings, factory=True).serve() ``` -------------------------------- ### Defining a Custom Instrument Configuration Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Create a custom configuration class for your instrument by inheriting from BaseInstrumentConfig. Define parameters specific to your instrument's needs. ```python from microbootstrap.instruments.base import BaseInstrumentConfig class MyInstrumentConfig(BaseInstrumentConfig): your_string_parameter: str your_list_parameter: list ``` -------------------------------- ### Format and Lint Code with Just Source: https://github.com/community-of-python/microbootstrap/blob/main/CLAUDE.md Formats and lints the codebase with automatic fixes using 'ruff format', 'ruff check --fix', and 'mypy'. ```bash just lint # Format and lint with fixes (ruff format, ruff check --fix, mypy) ``` -------------------------------- ### Base Service Settings Definition Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Define core service settings by inheriting from BaseServiceSettings. These include debug mode, environment, name, description, and version. ```python from microbootstrap.settings import BaseServiceSettings class ServiceSettings(BaseServiceSettings): service_debug: bool = True service_environment: str | None = None service_name: str = "micro-service" service_description: str = "Micro service description" service_version: str = "1.0.0" ... # Other settings here ``` -------------------------------- ### Configure Instrument Programmatically at Bootstrap Source: https://context7.com/community-of-python/microbootstrap/llms.txt Demonstrates configuring a specific instrument, FeatureFlagConfig, programmatically during the bootstrap process. This allows for overriding settings defined in the AppSettings class for specific environments or use cases. ```python from microbootstrap.config.litestar import LitestarConfig app = ( LitestarBootstrapper(AppSettings()) .configure_instrument(FeatureFlagConfig(feature_flag_endpoint="https://other-flags.example.com")) .bootstrap() ) ``` -------------------------------- ### Run Tests by Name with Just Source: https://github.com/community-of-python/microbootstrap/blob/main/CLAUDE.md Executes tests that match a specific name pattern. ```bash just test -k test_name # Run tests matching a name ``` -------------------------------- ### Configure Litestar Instruments Programmatically Source: https://context7.com/community-of-python/microbootstrap/llms.txt Override instruments programmatically. Scalars overwrite existing configurations, while containers merge. ```python app: litestar.Litestar = ( LitestarBootstrapper(settings) .configure_instrument(SentryConfig(sentry_dsn="https://other@sentry.io/789")) .configure_instrument(OpentelemetryConfig(opentelemetry_endpoint="http://other-collector:4317")) .configure_application(LitestarConfig(route_handlers=[get_order, create_order])) .bootstrap() ) ``` -------------------------------- ### Creating a Custom Instrument Class Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Define a custom instrument by inheriting from Instrument and specifying your configuration type. Implement required methods like is_ready() and optional methods like bootstrap() and teardown(). ```python from microbootstrap.instruments.base import Instrument class MyInstrument(Instrument[MyInstrumentConfig]): instrument_name: str ready_condition: str def is_ready(self) -> bool: pass def teardown(self) -> None: pass def bootstrap(self) -> None: pass @classmethod def get_config_type(cls) -> type[MyInstrumentConfig]: return MyInstrumentConfig ``` -------------------------------- ### Adapting a Custom Instrument for Litestar Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Integrate your custom instrument with Litestar by using the @LitestarBootstrapper.use_instrument() decorator. Implement bootstrap_before() and bootstrap_after() to modify application configuration. ```python import litestar from microbootstrap.bootstrappers.litestar import LitestarBootstrapper @LitestarBootstrapper.use_instrument() class LitestarMyInstrument(MyInstrument): def bootstrap_before(self) -> dict[str, typing.Any]: pass def bootstrap_after(self, application: litestar.Litestar) -> dict[str, typing.Any]: pass ``` -------------------------------- ### Configure In-Memory JSON Logging Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Extend BaseServiceSettings to configure in-memory JSON logging. Ensure service_debug is False. Customize log levels, buffer capacity, and excluded endpoints. ```python import logging from microbootstrap.settings import BaseServiceSettings class YourSettings(BaseServiceSettings): service_debug: bool = False logging_log_level: int = logging.INFO logging_flush_level: int = logging.ERROR logging_buffer_capacity: int = 10 logging_unset_handlers: list[str] = ["uvicorn", "uvicorn.access"] logging_extra_processors: list[typing.Any] = [] logging_exclude_endpoints: list[str] = ["/health/", "/metrics"] logging_turn_off_middleware: bool = False ``` -------------------------------- ### Configure OpenTelemetry with SQLAlchemy Source: https://context7.com/community-of-python/microbootstrap/llms.txt Configure OpenTelemetry tracing with custom endpoint, namespace, and include SQLAlchemy instrumentation. Ensure the OpenTelemetry collector is accessible at the specified endpoint. ```python from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor from microbootstrap import OpentelemetryConfig, LitestarSettings from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap.instruments.opentelemetry_instrument import OpenTelemetryInstrumentor class Settings(LitestarSettings): opentelemetry_endpoint: str | None = "http://otel-collector:4317" opentelemetry_namespace: str | None = "backend" opentelemetry_insecure: bool = True opentelemetry_exclude_urls: list[str] = ["/metrics", "/health/"] opentelemetry_log_traces: bool = False # log traces to stdout instead opentelemetry_generate_health_check_spans: bool = False # suppress health-check spans settings = Settings() # Add extra instrumentors (e.g., SQLAlchemy) from sqlalchemy import create_engine engine = create_engine("postgresql://user:pass@localhost/db") app = ( LitestarBootstrapper(settings) .configure_instrument( OpentelemetryConfig( opentelemetry_endpoint="http://otel-collector:4317", opentelemetry_instrumentors=[ OpenTelemetryInstrumentor( instrumentor=SQLAlchemyInstrumentor(), additional_params={"engine": engine}, ) ], opentelemetry_service_name="order-service-override", # overrides service_name in resource opentelemetry_container_name="orders-pod-7f9b", ) ) .bootstrap() ) ``` -------------------------------- ### Configure Health Checks in Python Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Define service name, version, and health check parameters by extending BaseServiceSettings. Ensure health checks are enabled and specify their path and schema inclusion. ```python from microbootstrap.settings import BaseServiceSettings class YourSettings(BaseServiceSettings): service_name: str = "micro-service" service_version: str = "1.0.0" health_checks_enabled: bool = True health_checks_path: str = "/health/" health_checks_include_in_schema: bool = False ``` -------------------------------- ### Configure Litestar Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Define your application settings by inheriting from LitestarSettings. Custom settings are stored here. ```python from microbootstrap import LitestarSettings class YourSettings(LitestarSettings): ... # Your settings are stored here settings = YourSettings() ``` -------------------------------- ### Extend Litestar Bootstrapper with Custom Instrument Source: https://context7.com/community-of-python/microbootstrap/llms.txt Register a custom instrument using the @Bootstrapper.use_instrument() decorator. Implement required methods like is_ready(), bootstrap(), bootstrap_before(), and bootstrap_after(). The instrument's configuration is automatically merged from settings. ```python import typing import litestar from microbootstrap.instruments.base import BaseInstrumentConfig, Instrument from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap import LitestarSettings # 1. Define the config (Pydantic model) class FeatureFlagConfig(BaseInstrumentConfig): feature_flag_endpoint: str | None = None feature_flag_api_key: str | None = None ``` -------------------------------- ### Configure Structured JSON Logging with structlog Source: https://context7.com/community-of-python/microbootstrap/llms.txt Sets up in-memory buffered JSON logging using structlog. OpenTelemetry trace/span IDs are injected automatically. Custom structlog processors can be added. ```python import logging from microbootstrap import LitestarSettings, LoggingConfig from microbootstrap.bootstrappers.litestar import LitestarBootstrapper import structlog class Settings(LitestarSettings): service_debug: bool = False # enables JSON/buffered logging logging_log_level: int = logging.INFO logging_flush_level: int = logging.ERROR # flush buffer on ERROR+ logging_buffer_capacity: int = 20 # buffer up to 20 messages logging_unset_handlers: list[str] = ["uvicorn", "uvicorn.access"] logging_exclude_endpoints: list[str] = ["/health/", "/metrics"] logging_turn_off_middleware: bool = False settings = Settings() app = LitestarBootstrapper(settings).bootstrap() # After bootstrap, use structlog anywhere in your app logger = structlog.get_logger("my_service") async def handler(): logger.info("Processing request", user_id=42, action="checkout") # Output (JSON): {"event":"Processing request","user_id":42,"action":"checkout", # "level":"info","logger":"my_service","timestamp":"...","tracing":{...}} ``` ```python # Add custom structlog processors from microbootstrap import LoggingConfig app = ( LitestarBootstrapper(settings) .configure_instrument( LoggingConfig( logging_extra_processors=[ structlog.processors.CallsiteParameterAdder( [structlog.processors.CallsiteParameter.FILENAME] ) ] ) ) .bootstrap() ) ``` -------------------------------- ### Configure Application with LitestarBootstrapper Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure the Litestar application directly by providing a LitestarConfig object with route handlers. This allows for custom routing and application-level settings. ```python import litestar from microbootstrap.config.litestar import LitestarConfig from microbootstrap.bootstrappers.litestar import LitestarBootstrapper from microbootstrap import SentryConfig, OpentelemetryConfig @litestar.get("/my-handler") async def my_handler() -> str: return "Ok" application: litestar.Litestar = ( LitestarBootstrapper(settings) .configure_application(LitestarConfig(route_handlers=[my_handler])) .bootstrap() ) ``` -------------------------------- ### Configure CORS Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Extend BaseServiceSettings to configure Cross-Origin Resource Sharing (CORS). Specify allowed origins, methods, headers, and credentials. ```python from microbootstrap.settings import BaseServiceSettings class YourSettings(BaseServiceSettings): cors_allowed_origins: list[str] = pydantic.Field(default_factory=list) cors_allowed_methods: list[str] = pydantic.Field(default_factory=list) cors_allowed_headers: list[str] = pydantic.Field(default_factory=list) cors_exposed_headers: list[str] = pydantic.Field(default_factory=list) cors_allowed_credentials: bool = False cors_allowed_origin_regex: str | None = None cors_max_age: int = 600 ``` -------------------------------- ### OpenTelemetry Base Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure OpenTelemetry endpoint, service name, and other parameters for general service settings. Ensure opentelemetry_endpoint is provided or opentelemetry_log_traces is True. ```python from microbootstrap.settings import BaseServiceSettings, FastStreamPrometheusMiddlewareProtocol from microbootstrap.instruments.opentelemetry_instrument import OpenTelemetryInstrumentor class YourSettings(BaseServiceSettings): service_name: str service_version: str opentelemetry_service_name: str | None = None opentelemetry_container_name: str | None = None opentelemetry_endpoint: str | None = None opentelemetry_namespace: str | None = None opentelemetry_insecure: bool = True opentelemetry_instrumentors: list[OpenTelemetryInstrumentor] = [] opentelemetry_exclude_urls: list[str] = [] ... # Other settings here ``` -------------------------------- ### FastAPI Prometheus Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure Prometheus metrics path and instrumentation parameters for FastAPI applications. Ensure service_name is in snake_case. ```python from microbootstrap.settings import FastApiSettings class YourSettings(FastApiSettings): service_name: str prometheus_metrics_path: str = "/metrics" prometheus_metrics_include_in_schema: bool = False prometheus_instrumentator_params: dict[str, typing.Any] = {} prometheus_instrument_params: dict[str, typing.Any] = {} prometheus_expose_params: dict[str, typing.Any] = {} ... # Other settings here ``` -------------------------------- ### Define LitestarSettings for Microbootstrap Source: https://context7.com/community-of-python/microbootstrap/llms.txt Define a settings class inheriting from LitestarSettings to configure service identity, server, Sentry, OpenTelemetry, Prometheus, logging, CORS, Swagger, health checks, and Pyroscope. Values can be overridden via environment variables or subclassing. ```python import os from microbootstrap import LitestarSettings, FastApiSettings, FastStreamSettings # All fields have defaults; override any via env vars or subclassing class MyLitestarSettings(LitestarSettings): # Service identity service_name: str = "payments-service" service_description: str = "Handles payment processing" service_version: str = "2.3.1" service_debug: bool = False service_environment: str | None = "production" # Server server_host: str = "0.0.0.0" server_port: int = 8080 server_workers_count: int = 4 server_reload: bool = False # Sentry sentry_dsn: str | None = "https://key@sentry.io/123" sentry_traces_sample_rate: float | None = 0.1 sentry_sample_rate: float = 1.0 sentry_tags: dict[str, str] | None = {"team": "backend"} # OpenTelemetry opentelemetry_endpoint: str | None = "http://otel-collector:4317" opentelemetry_namespace: str | None = "payments" # Prometheus — path where metrics are served prometheus_metrics_path: str = "/metrics" # Logging logging_log_level: int = 20 # logging.INFO logging_exclude_endpoints: list[str] = ["/health/", "/metrics"] # CORS cors_allowed_origins: list[str] = ["https://app.example.com"] cors_allowed_methods: list[str] = ["GET", "POST", "PUT", "DELETE"] cors_allowed_credentials: bool = True # Swagger swagger_path: str = "/docs" swagger_offline_docs: bool = False # Health checks health_checks_enabled: bool = True health_checks_path: str = "/health/" # Pyroscope pyroscope_endpoint: str | None = None # "http://pyroscope:4040" settings = MyLitestarSettings() # All values can also come from env vars, e.g. SERVICE_NAME, SENTRY_DSN, etc. # With ENVIRONMENT_PREFIX=MYAPP_ set, reads MYAPP_SERVICE_NAME, MYAPP_SENTRY_DSN, etc. ``` -------------------------------- ### Configure Sentry Integration Source: https://context7.com/community-of-python/microbootstrap/llms.txt Programmatically configure Sentry integration with custom DSN, integrations, and additional parameters. ```python app = ( LitestarBootstrapper(settings) .configure_instrument( SentryConfig( sentry_dsn="https://other@sentry.io/456", sentry_integrations=[SqlalchemyIntegration()], sentry_additional_params={"release": "1.0.0@abc123"}, ) ) .bootstrap() ) ``` -------------------------------- ### Configure Litestar Application Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Define general, Sentry, Prometheus, and Opentelemetry settings for your Litestar application. ```python from microbootstrap import LitestarSettings class YourSettings(LitestarSettings): # General settings service_debug: bool = False service_name: str = "my-awesome-service" # Sentry settings sentry_dsn: str = "your-sentry-dsn" # Prometheus settings prometheus_metrics_path: str = "/my-path" # Opentelemetry settings opentelemetry_container_name: str = "your-container" opentelemetry_endpoint: str = "/opentelemetry-endpoint" settings = YourSettings() ``` -------------------------------- ### FastStream Prometheus Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure Prometheus metrics path and middleware class for FastStream applications. Use RedisPrometheusMiddleware for Redis brokers. ```python from microbootstrap import FastStreamSettings from faststream.redis.prometheus import RedisPrometheusMiddleware class YourSettings(FastStreamSettings): service_name: str prometheus_metrics_path: str = "/metrics" prometheus_middleware_cls: type[FastStreamPrometheusMiddlewareProtocol] | None = RedisPrometheusMiddleware ... # Other settings here ``` -------------------------------- ### Configure Swagger/OpenAPI Docs with SwaggerConfig Source: https://context7.com/community-of-python/microbootstrap/llms.txt Controls the OpenAPI docs path, title, version, and optional offline serving. Setting `swagger_offline_docs=True` bundles Swagger JS/CSS from a static path so docs work without internet. Activates when `swagger_path` is a valid path string. ```python from microbootstrap import LitestarSettings, SwaggerConfig from microbootstrap.bootstrappers.litestar import LitestarBootstrapper class Settings(LitestarSettings): service_name: str = "Payments API" service_description: str = "Handles all payment operations" service_version: str = "2.0.0" swagger_path: str = "/docs" swagger_offline_docs: bool = True # serve Swagger assets from /static service_static_path: str = "/static" # path under which static files are served settings = Settings() # Disable docs entirely from microbootstrap import SwaggerConfig app = ( LitestarBootstrapper(settings) .configure_instrument( SwaggerConfig( swagger_path="/api/docs", swagger_extra_params={"external_docs": {"url": "https://wiki.example.com"}}, ) ) .bootstrap() ) ``` -------------------------------- ### Sentry Settings Configuration Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure Sentry integration by defining settings such as DSN, sampling rates, and breadcrumb limits. These settings are passed to the sentry-sdk. ```python from microbootstrap.settings import BaseServiceSettings class YourSettings(BaseServiceSettings): service_environment: str | None = None sentry_dsn: str | None = None sentry_traces_sample_rate: float | None = None sentry_sample_rate: float = pydantic.Field(default=1.0, le=1.0, ge=0.0) sentry_max_breadcrumbs: int = 15 sentry_max_value_length: int = 16384 sentry_attach_stacktrace: bool = True sentry_integrations: list[Integration] = [] sentry_additional_params: dict[str, typing.Any] = {} sentry_tags: dict[str, str] | None = None sentry_opentelemetry_trace_url_template: str | None = None ... # Other settings here ``` -------------------------------- ### Overwrite Simple Data Type Parameters in Python Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Demonstrates how simple data types like strings are overwritten when configuring instruments. The new Sentry DSN replaces the one defined in the settings. ```python from microbootstrap import LitestarSettings, SentryConfig class YourSettings(LitestarSettings): sentry_dsn: str = "https://my-sentry-dsn" application: litestar.Litestar = ( LitestarBootstrapper(YourSettings()) .configure_instrument( SentryConfig(sentry_dsn="https://my-new-configured-sentry-dsn") ) .bootstrap() ) ``` -------------------------------- ### FastStream OpenTelemetry Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure the OpenTelemetry middleware class for FastStream applications. RedisTelemetryMiddleware is used for Redis brokers. ```python from microbootstrap import FastStreamSettings, FastStreamTelemetryMiddlewareProtocol from faststream.redis.opentelemetry import RedisTelemetryMiddleware class YourSettings(FastStreamSettings): ... opentelemetry_middleware_cls: type[FastStreamTelemetryMiddlewareProtocol] | None = RedisTelemetryMiddleware ... ``` -------------------------------- ### Environment Variable Prefix Configuration Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure a prefix for environment variables to source settings. This helps in organizing and avoiding naming conflicts for environment variables. ```bash $ export ENVIRONMENT_PREFIX=YOUR_PREFIX_ ``` -------------------------------- ### Litestar Prometheus Settings Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Configure Prometheus metrics path and additional parameters for Litestar applications. The service_name has no naming restrictions. ```python from microbootstrap.settings import LitestarSettings class YourSettings(LitestarSettings): service_name: str prometheus_metrics_path: str = "/metrics" prometheus_additional_params: dict[str, typing.Any] = {} ... # Other settings here ``` -------------------------------- ### CI Lint Check with Just Source: https://github.com/community-of-python/microbootstrap/blob/main/CLAUDE.md Performs a lint check without applying any fixes, suitable for continuous integration environments. ```bash just lint-ci # Lint check without fixes ``` -------------------------------- ### Configure Litestar Prometheus Metrics Source: https://context7.com/community-of-python/microbootstrap/llms.txt Configure Prometheus metrics exposure for Litestar, specifying the metrics path and additional parameters for filtering unhandled paths. Ensure the service name is set in settings. ```python from microbootstrap import FastApiSettings, LitestarSettings, FastStreamSettings from microbootstrap import FastApiPrometheusConfig, LitestarPrometheusConfig, FastStreamPrometheusConfig from microbootstrap.bootstrappers.fastapi import FastApiBootstrapper from microbootstrap.bootstrappers.litestar import LitestarBootstrapper # Litestar class LitestarAppSettings(LitestarSettings): prometheus_metrics_path: str = "/metrics" service_name: str = "api-gateway" litestar_app = ( LitestarBootstrapper(LitestarAppSettings()) .configure_instrument( LitestarPrometheusConfig( prometheus_metrics_path="/metrics", prometheus_additional_params={"filter_unhandled_paths": True}, ) ) .bootstrap() ) ``` -------------------------------- ### Configure Pyroscope Profiling in Litestar Source: https://context7.com/community-of-python/microbootstrap/llms.txt Enables continuous CPU profiling via the pyroscope package. Profile span IDs are injected into traces for correlation when OpenTelemetry is also active. Activates when pyroscope_endpoint is set and pyroscope is importable. Configuration can be overridden at bootstrap time. ```python from microbootstrap import LitestarSettings, PyroscopeConfig from microbootstrap.bootstrappers.litestar import LitestarBootstrapper class Settings(LitestarSettings): service_name: str = "compute-service" opentelemetry_endpoint: str = "http://otel-collector:4317" pyroscope_endpoint: str = "http://pyroscope:4040" pyroscope_sample_rate: int = 100 # samples per second pyroscope_tags: dict[str, str] = {"region": "us-east-1"} settings = Settings() app = LitestarBootstrapper(settings).bootstrap() # Override pyroscope at bootstrap time app = ( LitestarBootstrapper(settings) .configure_instrument( PyroscopeConfig( pyroscope_endpoint="http://pyroscope:4040", pyroscope_sample_rate=50, pyroscope_additional_params={"detect_subprocesses": True}, ) ) .bootstrap() ) ``` -------------------------------- ### Configure FastAPI Prometheus Metrics Source: https://context7.com/community-of-python/microbootstrap/llms.txt Configure Prometheus metrics exposure for FastAPI, including custom labels and instrumentation parameters. Ensure the metrics path is correctly set. ```python from microbootstrap import FastApiSettings, LitestarSettings, FastStreamSettings from microbootstrap import FastApiPrometheusConfig, LitestarPrometheusConfig, FastStreamPrometheusConfig from microbootstrap.bootstrappers.fastapi import FastApiBootstrapper from microbootstrap.bootstrappers.litestar import LitestarBootstrapper # FastAPI class FastApiAppSettings(FastApiSettings): prometheus_metrics_path: str = "/metrics" fastapi_app = ( FastApiBootstrapper(FastApiAppSettings()) .configure_instrument( FastApiPrometheusConfig( prometheus_metrics_path="/metrics", prometheus_metrics_include_in_schema=False, prometheus_custom_labels={"env": "production"}, prometheus_instrumentator_params={"should_group_status_codes": True}, ) ) .bootstrap() ) ``` -------------------------------- ### Mix Feature Flag Config into App Settings Source: https://context7.com/community-of-python/microbootstrap/llms.txt Combines LitestarSettings with FeatureFlagConfig to create a unified application settings class. This allows feature flag configurations to be managed alongside other application settings. ```python class AppSettings(LitestarSettings, FeatureFlagConfig): service_name: str = "feature-demo" feature_flag_endpoint: str | None = "https://flags.example.com" feature_flag_api_key: str | None = "secret-key" settings = AppSettings() app = LitestarBootstrapper(settings).bootstrap() ``` -------------------------------- ### Configure CORS with CorsConfig Source: https://context7.com/community-of-python/microbootstrap/llms.txt Controls CORS headers. Activates when `cors_allowed_origins` is non-empty or `cors_allowed_origin_regex` is set. For Litestar, it passes a `CORSConfig` to the app constructor; for FastAPI, it adds `CORSMiddleware`. ```python from microbootstrap import LitestarSettings, CorsConfig from microbootstrap.bootstrappers.litestar import LitestarBootstrapper class Settings(LitestarSettings): cors_allowed_origins: list[str] = ["https://app.example.com", "https://admin.example.com"] cors_allowed_methods: list[str] = ["GET", "POST", "PUT", "DELETE", "OPTIONS"] cors_allowed_headers: list[str] = ["Authorization", "Content-Type"] cors_exposed_headers: list[str] = ["X-Request-ID"] cors_allowed_credentials: bool = True cors_max_age: int = 3600 settings = Settings() app = LitestarBootstrapper(settings).bootstrap() # Override CORS at bootstrap time app = ( LitestarBootstrapper(settings) .configure_instrument( CorsConfig( cors_allowed_origin_regex=r"https://.*\.example\.com", # regex instead of list cors_allowed_methods=["GET", "POST"], ) ) .bootstrap() ) # Note: cors_allowed_origins (list) from settings and any configure_instrument calls are MERGED ``` -------------------------------- ### FastAPI Application with Custom Lifespan and Config Overrides Source: https://context7.com/community-of-python/microbootstrap/llms.txt Configure a FastAPI application with a custom lifespan and instrument overrides, such as Prometheus metrics path and custom labels. ```python from contextlib import asynccontextmanager from typing import AsyncIterator @asynccontextmanager async def custom_lifespan(app: fastapi.FastAPI) -> AsyncIterator[None]: print("App starting up") yield print("App shutting down") def create_app_with_lifespan() -> fastapi.FastAPI: return ( FastApiBootstrapper(settings) .configure_instrument( FastApiPrometheusConfig( prometheus_metrics_path="/metrics", prometheus_custom_labels={"region": "eu-west-1"}, ) ) .configure_application(FastApiConfig(lifespan=custom_lifespan)) .bootstrap() ) ``` -------------------------------- ### Merge Complex Data Type Parameters in Python Source: https://github.com/community-of-python/microbootstrap/blob/main/README.md Illustrates how complex data types like dictionaries are merged when configuring instruments. The Prometheus additional parameters are combined from settings and configuration. ```python from microbootstrap import LitestarSettings, PrometheusConfig class YourSettings(LitestarSettings): prometheus_additional_params: dict[str, Any] = {"first_value": 1} application: litestar.Litestar = ( LitestarBootstrapper(YourSettings()) .configure_instrument( PrometheusConfig(prometheus_additional_params={"second_value": 2}) ) .bootstrap() ) ``` -------------------------------- ### Define Base Feature Flag Instrument Source: https://context7.com/community-of-python/microbootstrap/llms.txt Defines a base instrument for feature flags, specifying configuration requirements and readiness conditions. This class should be extended for framework-specific implementations. ```python class FeatureFlagInstrument(Instrument[FeatureFlagConfig]): instrument_name = "FeatureFlags" ready_condition = "Provide feature_flag_endpoint and feature_flag_api_key" def is_ready(self) -> bool: return bool(self.instrument_config.feature_flag_endpoint and self.instrument_config.feature_flag_api_key) def bootstrap(self) -> None: # Initialize your feature flag client here print(f"Connecting to {self.instrument_config.feature_flag_endpoint}") def teardown(self) -> None: print("Disconnecting feature flag client") @classmethod def get_config_type(cls) -> type[FeatureFlagConfig]: return FeatureFlagConfig ```