|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import sys |
| 4 | + |
| 5 | + |
| 6 | +def configure_logging() -> None: |
| 7 | + """Configure logging based on LOG_FORMAT environment variable. |
| 8 | +
|
| 9 | + If LOG_FORMAT is set, configures the root logger with a StreamHandler |
| 10 | + using the specified format string. This must be called before FastMCP |
| 11 | + initialization to ensure our configuration takes precedence. |
| 12 | +
|
| 13 | + If LOG_FORMAT is not set or is empty, does nothing and lets FastMCP |
| 14 | + configure logging with its default settings. |
| 15 | +
|
| 16 | + Environment variables: |
| 17 | + LOG_FORMAT: Python logging format string (optional) |
| 18 | + Examples: |
| 19 | + - "%(asctime)s agent %(levelname)s [%(name)s] %(message)s" |
| 20 | + - "%(levelname)s: %(message)s" |
| 21 | + - "[%(name)s] %(message)s" |
| 22 | +
|
| 23 | + Raises: |
| 24 | + ValueError: If LOG_FORMAT contains an invalid format string |
| 25 | + """ |
| 26 | + log_format = os.getenv("LOG_FORMAT", "").strip() |
| 27 | + |
| 28 | + # If LOG_FORMAT is not set or empty, do nothing |
| 29 | + if not log_format: |
| 30 | + return |
| 31 | + |
| 32 | + # Create handler for stderr (same as FastMCP default) |
| 33 | + handler = logging.StreamHandler(sys.stderr) |
| 34 | + |
| 35 | + # Create formatter with the specified format string |
| 36 | + # This will raise an error if the format string is invalid (fail fast) |
| 37 | + formatter = logging.Formatter(log_format) |
| 38 | + handler.setFormatter(formatter) |
| 39 | + |
| 40 | + # Configure root logger |
| 41 | + # This must be done before FastMCP calls logging.basicConfig() |
| 42 | + logging.root.addHandler(handler) |
| 43 | + logging.root.setLevel(logging.INFO) |
0 commit comments