FastlyLogHandler
Extends logging.Handler.
A logging handler that sends logs to a Fastly endpoint.
This handler integrates with Python's standard logging framework, allowing you to use familiar logging patterns with Fastly's Real-Time Log Streaming.
The handler supports routing logs from different loggers to different endpoints using an endpoint_mapper function.
12345678910111213141516171819202122232425262728import loggingfrom fastly_compute import FastlyLogHandler
# Simple: single endpoint for all loggershandler = FastlyLogHandler("my_logs")logger = logging.getLogger("my_app")logger.addHandler(handler)
# Advanced: route different loggers to different endpointsdef route_logs(logger_name: str) -> str: if logger_name.startswith("api"): return "api-logs" elif logger_name.startswith("worker"): return "worker-logs" return "app-logs" # default
handler = FastlyLogHandler(endpoint_mapper=route_logs)
# Or use a dict for simple mappingsendpoint_map = {"api": "api-logs", "worker": "worker-logs"}handler = FastlyLogHandler( "default", endpoint_mapper=lambda name: endpoint_map.get(name, "app-logs"))
# Use loggerlogger.info("Request received", extra={"user_id": 123})logger.error("Error processing request", exc_info=True)Constructor
FastlyLogHandler(default_endpoint: str | None, endpoint_mapper: Callable[[str], str | None] | None = None, level=logging.NOTSET)Initialize the handler.
Parameters
- default_endpoint: str | None
The default endpoint name (used when no mapper provided)
- endpoint_mapper: Callable[[str], str | None] | Noneoptional =
None Optional callable that maps logger name to endpoint name. Signature: (loggername: str) -> endpointname: str
- level: Anyoptional =
logging.NOTSET Minimum logging level to handle (default: NOTSET)
Throws
- ValueError — If neither defaultendpoint nor endpointmapper is provided
12345678910111213# Simple: single endpointhandler = FastlyLogHandler("my_logs")
# Advanced: route by logger namehandler = FastlyLogHandler( endpoint_mapper=lambda name: f"{name}-logs")
# With fallbackhandler = FastlyLogHandler( default_endpoint="app-logs", endpoint_mapper=lambda name: "api-logs" if "api" in name else None)Methods
close
View sourceclose()Close the handler and release all endpoint resources.
This is called automatically when the handler is garbage collected or when logging.shutdown() is called.
emit
View sourceEmit a record to the Fastly logging endpoint.
This method is called automatically by the logging framework. You should not need to call it directly.
The endpoint is determined by calling endpointmapper with the logger name, or using the defaultendpoint.
Parameters
- record: logging.LogRecord
The log record to emit