Pyvider uses the provide.foundation logging system for structured logging throughout your provider. This guide covers how to effectively log provider operations.
🤖 AI-Generated Content
This documentation was generated with AI assistance and is still being audited. Some, or potentially a lot, of this information may be inaccurate. Learn more.
fromprovide.foundationimportloggerasyncdefcreate_server(name:str,size:str):# Bind context for all subsequent logslog=logger.bind(operation="create_server",server_name=name,server_size=size,)log.info("Creating server")try:server=awaitapi.create_server(name,size)log.info("Server created successfully",server_id=server.id)returnserverexceptExceptionase:log.error("Server creation failed",error=str(e))raise
# Create contextual loggerlog=logger.bind(operation="apply_resource",resource_type="server",resource_id="srv-123")# All subsequent calls include contextlog.info("Starting operation")# Includes operation, resource_type, resource_idlog.info("Operation complete")# Context automatically included
# Bad: Logs sensitive datalogger.info("Creating API key",api_key=config.api_key)# Good: Mask or omit sensitive datalogger.info("Creating API key",key_prefix=config.api_key[:4])
# Console format (human-readable, default for development)exportFOUNDATION_LOG_FORMAT=console
# JSON format (machine-readable, for production)exportFOUNDATION_LOG_FORMAT=json
frompyvider.resourcesimportregister_resource,BaseResourcefrompyvider.resources.contextimportResourceContextfromprovide.foundationimportlogger@register_resource("server")classServer(BaseResource):asyncdef_create_apply(self,ctx:ResourceContext)->tuple[ServerState|None,None]:ifnotctx.config:returnNone,Nonelog=logger.bind(component="resource",resource_type="server",operation="create",server_name=ctx.config.name,)log.info("Creating server resource")try:# Create serverlog.debug("Calling API to create server",size=ctx.config.size)server=awaitself.api.create_server(name=ctx.config.name,size=ctx.config.size,)log.info("Server created successfully",server_id=server.id,ip_address=server.ip,status=server.status)returnServerState(...),NoneexceptQuotaExceededErrorase:log.error("Server creation failed: quota exceeded",current_usage=e.current,quota_limit=e.limit)raiseResourceError(f"Quota exceeded: {e}")exceptAPIErrorase:log.error("Server creation failed: API error",error_code=e.code,error_message=str(e))raiseResourceError(f"API error: {e}")