# azure-functions-logging

> Structured logging for Azure Functions Python — invocation-aware, Application Insights-ready, zero breaking changes.

## Package Info

- PyPI: `pip install azure-functions-logging`
- Version: see package metadata (`pip show azure-functions-logging`); release history at https://pypi.org/project/azure-functions-logging/#history
- Python: >=3.11, <3.15
- License: MIT
- Docs: https://yeongseon.dev/azure-functions-python/logging/
- Repository: https://github.com/yeongseon/azure-functions-logging-python

## What It Does

Surfaces `invocation_id`, detects cold starts, warns on `host.json` misconfig, and outputs Application Insights-ready structured logs — without replacing Python's standard `logging`.

Key features:
- **Invocation context** — auto-injects `invocation_id`, `function_name`, `cold_start` into every log
- **Structured JSON output** — Application Insights-ready NDJSON format for production
- **Noise control** — `SamplingFilter` rate-limits chatty third-party loggers
- **PII protection** — `RedactionFilter` masks sensitive fields before they reach log aggregation
- **Root logger contract** — in Azure/Core Tools mode, no handlers are added; `ContextFilter` is installed on existing root handlers and on the root logger itself (so direct calls on the root logger carry context). To guarantee coverage for records that propagate from named child loggers to handlers attached later, pass `use_record_factory=True` to `setup_logging()`. In standalone mode (`logger_name=None`), the root logger's level is set and a `StreamHandler` is added if none exist.
- **Zero runtime dependency** — on azure-functions (works with any context-like object)

## Core API

- `setup_logging(*, level=logging.INFO, format="color", logger_name=None, functions_formatter=None, host_json_path=None, use_record_factory=False, extra_context_vars=None, activate_trace_context=None)` — Eight keyword-only parameters; defaults unchanged.
- `configure_secure_redaction(*, enabled=True) -> None` — Apply bounded fail-closed key/pattern masking on every current handler after setup/exporter enrichment. Explicit `enabled=False` removes only package-owned secure filters; ordinary setup preserves the selected policy.
- `get_logger(name)` → `FunctionLogger` — Create a logger with context binding support
- `FunctionLogger` — Enhanced logger wrapper with `bind()`, `log()`, `hasHandlers()`, `setLevel()`, `isEnabledFor()`, `getEffectiveLevel()` for stdlib parity
- `JsonFormatter(*, max_string_length=2048, truncate_native_strings=False)` — JSON log formatter (NDJSON). Set `truncate_native_strings=True` to clip string values in `extra` at `max_string_length` chars.
- `RedactionFilter(sensitive_keys=None, name="", patterns=None, *, fail_closed=False)` — Default fail-open compatibility; opt-in fail-closed conversion masks affected values and never raises.
- `attach_secure_redaction(handler) -> None` — Protect a late handler before registration, after enrichment/flatten filters. Idempotent; also protects IsolatedHandler targets. No automatic future-handler interception.
- `IsolatedHandler(target)` — opt-in wrapper that clones each `LogRecord` before wrapper filters run, keeping mutating transformations local to one output; register the wrapper instead of `target`
- `SamplingFilter(rate=100, window=1.0, name="", per_logger=False)` — Filter for log sampling/rate-limiting noisy loggers. Set `per_logger=True` for independent buckets per logger name.
- `logging_context(context)` — **Recommended** context manager: injects on enter, always restores on exit
- `inject_context(context)` → `ContextTokens` — Set contextvars; returns tokens for paired restore
- `restore_context(tokens)` — Restore previous contextvars from tokens (paired with `inject_context`)
- `reset_context()` — Clear all context vars unconditionally (for test teardown)
- `with_context` — Decorator to inject context per-request (sync/async)
- `setup_logging(use_record_factory=True)` — opt-in global LogRecordFactory so context flows to every record (mutually exclusive with the default `ContextFilter` mode)
- `get_logging_metadata(func)` — Inspect `@with_context` metadata on a function; returns `dict[str, Any] | None`
- `ContextTokens` — Type alias for the token bundle returned by `inject_context()`

## Quick Start

```python
import azure.functions as func
from azure_functions_logging import get_logger, logging_context, setup_logging

setup_logging()
logger = get_logger(__name__)

app = func.FunctionApp()

@app.route(route="hello")
def hello(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    with logging_context(context):  # binds invocation_id, function_name, cold_start; always restores on exit
        logger.info("Request received")
        return func.HttpResponse("OK")
```

Or use the decorator:

```python
import azure.functions as func
from azure_functions_logging import with_context, get_logger, setup_logging

setup_logging()
logger = get_logger(__name__)

@with_context
def handler(req, context):
    logger.info("This automatically has context")
    return func.HttpResponse("OK")
```

## Documentation

- [Getting Started](https://yeongseon.dev/azure-functions-python/logging/getting-started/)
- [API Reference](https://yeongseon.dev/azure-functions-python/logging/api/)
- [Configuration](https://yeongseon.dev/azure-functions-python/logging/configuration/)
- [Examples](https://yeongseon.dev/azure-functions-python/logging/examples/basic_setup/)
- [Troubleshooting](https://yeongseon.dev/azure-functions-python/logging/troubleshooting/)

## Ecosystem

Part of the Azure Functions Python DX Toolkit:
- azure-functions-validation — Request/response validation
- azure-functions-openapi — OpenAPI spec and Swagger UI
- azure-functions-langgraph — Deploy LangGraph agents as Azure Functions
- azure-functions-doctor — Pre-deploy diagnostics CLI
- azure-functions-scaffold — Project scaffolding CLI
