Python / Uvicorn Fundamentals Interview Questions
How do you configure Uvicorn's log config file for custom logging formats?
Uvicorn's --log-config flag accepts a logging configuration in JSON or YAML format (using Python's dictConfig) or in INI format (fileConfig). This enables structured logging, custom formats, and routing logs to different handlers.
# logging.json - custom log config in dictConfig format { "version": 1, "disable_existing_loggers": false, "formatters": { "default": { "()": "uvicorn.logging.DefaultFormatter", "fmt": "%(levelprefix)s %(asctime)s %(message)s", "use_colors": false }, "access": { "()": "uvicorn.logging.AccessFormatter", "fmt": '%(levelprefix)s %(asctime)s %(client_addr)s - "%(request_line)s" %(status_code)s', "use_colors": false } }, "handlers": { "default": { "formatter": "default", "class": "logging.StreamHandler", "stream": "ext://sys.stderr" }, "access": { "formatter": "access", "class": "logging.StreamHandler", "stream": "ext://sys.stdout" } }, "loggers": { "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": false}, "uvicorn.error": {"level": "INFO"}, "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": false} } }
# Use the custom log config: uvicorn main:app --log-config logging.json # Or YAML format (requires PyYAML - included in uvicorn[standard]): uvicorn main:app --log-config logging.yaml # Programmatically: import logging.config, json with open("logging.json") as f: log_config = json.load(f) uvicorn.run("main:app", log_config=log_config)
To override colour settings in the log config, set formatters.default.use_colors and formatters.access.use_colors to true or false explicitly. This takes precedence over auto-detection.
More Related questions...