Overview
The Context API provides access to function-scoped resources like logging and tracing spans. Every function handler runs within a context that is accessible viaget_context().
Accessing Context
get_context
Get the current function’s context.Context
The context for the currently executing function
get_context() returns a default context when called outside of a function handler (e.g., in application startup code).with_context
Execute a function within a custom context.Context
required
Custom context to use for the execution
F
required
Async function to execute within the context
The SDK automatically wraps function handlers with
with_context, so you typically don’t need to call this manually.Context Structure
Context
The context available within function handlers.logger: Logger instance scoped to the current functionspan: Active tracing span (used internally by the SDK, typically not accessed directly)
Logger
The Logger provides structured logging with automatic trace context integration.Logger Methods
info
Log an informational message.&str
required
Log message
Option<Value>
Optional structured data to include with the log
warn
Log a warning message.error
Log an error message.debug
Log a debug message.OpenTelemetry Integration
When theotel feature is enabled, logs are automatically exported via OpenTelemetry:
- Timestamp (observed and actual)
- Severity level (Debug, Info, Warn, Error)
- Message body
- Function name attribute
- Structured data as attributes
- Trace context (trace_id, span_id, trace_flags)
When the
otel feature is disabled, logs fall back to the tracing crate.Creating Custom Loggers
Logger::new
Create a logger with a custom function name.Option<String>
Function name to include in log records
Complete Example
Here’s a complete example showing context usage:Log Levels
When to use each level:- debug: Detailed information for debugging (verbose)
- info: General informational messages about application flow
- warn: Warning messages for potentially problematic situations
- error: Error messages for failures that require attention
Best Practices
-
Always use structured data: Pass JSON objects to the
dataparameter instead of formatting strings: -
Log at appropriate levels: Use
debugfor verbose details,infofor key events,warnfor issues, anderrorfor failures. -
Include context in structured data: Add relevant IDs and metadata to help with debugging:
-
Don’t log sensitive data: Avoid logging passwords, tokens, or PII:
See Also
- Functions API - Function handlers automatically receive context
- Telemetry API - Configure OpenTelemetry for log export
- Invocation API - Context is propagated across function calls