Skip to main content

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 via get_context().

Accessing Context

get_context

Get the current function’s context.
Context
The context for the currently executing function
Example:
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
Example:
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.
Fields:
  • logger: Logger instance scoped to the current function
  • span: 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
Example:

warn

Log a warning message.
Example:

error

Log an error message.
Example:

debug

Log a debug message.
Example:

OpenTelemetry Integration

When the otel feature is enabled, logs are automatically exported via OpenTelemetry:
OpenTelemetry LogRecords include:
  • 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
Example:

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

  1. Always use structured data: Pass JSON objects to the data parameter instead of formatting strings:
  2. Log at appropriate levels: Use debug for verbose details, info for key events, warn for issues, and error for failures.
  3. Include context in structured data: Add relevant IDs and metadata to help with debugging:
  4. Don’t log sensitive data: Avoid logging passwords, tokens, or PII:

See Also