Ir para o conteúdo

tempest_fastapi_sdk.core

Primitivas transversais: tipagem estrita, logging, observabilidade por camada, redação de dados sensíveis e locale da documentação.

« Admin, dados e API


strict_types

strict_types(func: F) -> F

Validate argument and return values with no type coercion.

Wraps func so that, on every call, each argument and the return value are validated against the function's annotations in Pydantic's strict mode: a value must already be of the annotated type. A str passed where int is annotated raises -- it is not coerced to 1. Use this when you want the strongest runtime guarantee that values match their declared types.

Parameters:

Name Type Description Default
func F

The function or method to wrap. Every parameter and the return must be annotated (unannotated parameters are treated as Any by Pydantic and therefore not enforced).

required

Returns:

Name Type Description
F F

The wrapped callable with the same signature. Raises

F

class:pydantic.ValidationError when a value does not match

F

its annotation.

Example

@strict_types ... def add(a: int, b: int) -> int: ... return a + b add(1, 2) 3 add("1", 2) # doctest: +SKIP Traceback (most recent call last): pydantic_core._pydantic_core.ValidationError: ...

typed

typed(func: F) -> F

Validate argument and return values, coercing when safe.

Like :func:strict_types, but in Pydantic's default (lax) mode: values that are not of the annotated type are coerced when Pydantic can do so unambiguously ("1" -> 1, "true" -> True). A value that cannot be coerced still raises. Use this when you want runtime safety but also want the convenience of automatic coercion of stringly-typed input.

Parameters:

Name Type Description Default
func F

The function or method to wrap. Every parameter and the return should be annotated; unannotated parameters are treated as Any and not enforced.

required

Returns:

Name Type Description
F F

The wrapped callable with the same signature. Raises

F

class:pydantic.ValidationError when a value cannot be

F

validated or coerced to its annotation.

Example

@typed ... def add(a: int, b: int) -> int: ... return a + b add("1", 2) # coerced 3

require_annotations

require_annotations(func: F) -> F

Require every parameter and the return to be annotated.

Unlike :func:strict_types / :func:typed, this does not validate runtime values -- it enforces that the function carries annotations at all, failing fast at decoration time (i.e. when the module is imported) instead of relying on a separate linter pass. self and cls are exempt, as are *args / **kwargs.

Parameters:

Name Type Description Default
func F

The function or method to inspect.

required

Returns:

Name Type Description
F F

The same function, unchanged, when fully annotated.

Raises:

Type Description
TypeError

If any parameter (other than self / cls / *args / **kwargs) or the return value lacks an annotation. The message lists every offending name.

Example

@require_annotations ... def ok(a: int) -> int: ... return a @require_annotations # doctest: +SKIP ... def bad(a) -> int: ... return a Traceback (most recent call last): TypeError: bad: missing type annotation for parameter 'a'

normalize_docs_locale

normalize_docs_locale(value: str) -> DocsLocale

Coerce a loose locale string into a supported :data:DocsLocale.

Accepts any case and either separator ("pt_br", "PT-BR") and the bare primary subtag ("pt", "en"), through the same :func:~tempest_fastapi_sdk.core.enums.normalize_locale_tag the rest of the SDK uses. A tag the catalog does not carry is refused instead of falling back to English: a pt-PT deployment that silently renders English documentation is the failure this check exists for.

Parameters:

Name Type Description Default
value str

The raw configured value.

required

Returns:

Name Type Description
DocsLocale DocsLocale

"en-US" or "pt-BR".

Raises:

Type Description
ValueError

When value is not a locale tag, or names one the catalog does not carry.

DocsLocale module-attribute

DocsLocale = Literal['en-US', 'pt-BR']

A language the route-docs catalog carries.

configure_root_once

configure_root_once(**kwargs: Any) -> Logger

Configure the root logger the first time, and only the first time.

The idempotent entry point for the common shape: one handler set on the root logger, every module logger propagating into it. Calling :func:configure_logging per module instead gives each of them its own handler set with propagate = False, which for a service with N modules means N stdout handlers plus N * 6 file handlers open on the same six paths — and that many RotatingFileHandler instances racing to roll one file over lose records and interleave the numbered backups.

Parameters:

Name Type Description Default
**kwargs Any

Forwarded to :func:configure_logging on the first call, ignored afterwards. logger_name is not accepted — this function is about the root logger.

{}

Returns:

Type Description
Logger

logging.Logger: The root logger, configured.

Raises:

Type Description
TypeError

When logger_name is passed.

reinitialize_logging

reinitialize_logging() -> None

Re-enable every logger and clear the configure-once latch.

logging.config.fileConfig() defaults to disable_existing_loggers=True, which sets disabled = True on every logger that already existed. Alembic calls it from the env.py this SDK ships, so a migration run silences the application's own loggers for the rest of the process — the records are dropped before any handler sees them, which looks like a logging configuration problem and is not one.

Call this after any code that reconfigures Python's logging system. The next :func:configure_root_once will re-attach handlers.

RedactionPolicy dataclass

RedactionPolicy(
    keys: Collection[str] = DEFAULT_REDACT_KEYS,
    extra_keys: Collection[str] = (),
    exact_keys: Collection[str] = (),
    patterns: Sequence[Pattern[str] | str] = DEFAULT_REDACT_PATTERNS,
    extra_patterns: Sequence[Pattern[str] | str] = (),
    replacement: str = REDACTED,
)

What :class:RedactionFilter hides from a log record.

Two mechanisms run together:

  • Sensitive keys — any mapping key (an extra= field, a key of a dict passed as a log argument or nested in one) whose normalized name contains one of :attr:keys / :attr:extra_keys has its whole value replaced. The same keys also drive a key=value / key: value pattern over free text, so ?token=abc in a query string and {'password': 'x'} quoted in an exception message are caught.
  • Text patterns — every string (message, traceback, stack, string values) has each of :attr:patterns / :attr:extra_patterns replaced. The defaults cover e-mail addresses, Bearer credentials and JWTs, plus the token segment of the SDK's own capability routes (:data:CAPABILITY_PATH_PATTERN).

Use :attr:extra_keys / :attr:extra_patterns to add domain terms without restating the defaults; set :attr:keys / :attr:patterns only to replace them.

Attributes:

Name Type Description
keys Collection[str]

Base sensitive key fragments. Defaults to :data:DEFAULT_REDACT_KEYS.

extra_keys Collection[str]

Additional key fragments, added to :attr:keys.

exact_keys Collection[str]

Keys matched by equality after the same normalization, for a short name a substring would over-match: exact_keys={"code"} hides code and Code but leaves status_code alone. They apply everywhere the fragments do — extra= fields, nested dicts and key=value in free text.

patterns Sequence[Pattern[str] | str]

Base text patterns. Defaults to :data:DEFAULT_REDACT_PATTERNS. Strings are compiled.

extra_patterns Sequence[Pattern[str] | str]

Additional text patterns, applied after :attr:patterns.

replacement str

The text written in place of each redacted value. Defaults to :data:REDACTED.

is_sensitive_key

is_sensitive_key(key: str) -> bool

Return whether a key's value must be redacted whole.

Parameters:

Name Type Description Default
key str

The key to test, normalized to lower case with - turned into _. It matches when it equals one of :attr:exact_keys or contains one of the fragments.

required

Returns:

Name Type Description
bool bool

True when the key is sensitive.

redact_text

redact_text(text: str) -> str

Redact sensitive key=value pairs and pattern matches.

Parameters:

Name Type Description Default
text str

Any free text — a message, a traceback, a stack.

required

Returns:

Name Type Description
str str

The text with every match replaced by

str

attr:replacement. The key and separator of a key=value

str

pair are kept, so the line still says what was hidden.

redact_value

redact_value(value: Mapping[K, object]) -> dict[K, RedactedValue]
redact_value(
    value: list[T] | set[T] | tuple[object, ...] | frozenset[object],
) -> list[RedactedValue]
redact_value(value: object) -> RedactedValue
redact_value(value: object) -> object

Redact a value of any shape, recursing into containers.

Mappings have sensitive keys replaced and the remaining values redacted; lists, tuples and sets are redacted item by item (and come back as lists); strings go through :meth:redact_text; bool/int/float/None are kept. Anything else is rendered with str first — which is what :class:~tempest_fastapi_sdk.JSONFormatter would write for it anyway — so an object whose repr quotes an e-mail does not slip past.

Parameters:

Name Type Description Default
value object

The value to redact.

required

Returns:

Name Type Description
RedactedValue object

A redacted copy — a dict with the same keys

object

for a mapping, a list for any other container. The input

object

is never mutated.

redact_in_place

redact_in_place(value: T) -> T

Redact a structure where it stands, keeping every node's type.

The counterpart of :meth:redact_value for a payload that must keep its shape — a Sentry event, a JSON document about to be sent. Differences:

  • No depth limit. Dicts, lists and sets are walked with an explicit stack, so a node fifty levels down is still a dict, never the str of one. A container met twice (a cycle, or one object shared by two parents) is walked once.
  • In place. A mutable mapping has sensitive keys' values replaced and the others redacted; a list (or any mutable sequence) has its items replaced by index; a set is refilled; a bytearray is rewritten. Each comes back as the same object.
  • Types kept. A str goes through :meth:redact_text; bytes is decoded as UTF-8 with surrogateescape (so any byte sequence round-trips), redacted and encoded back; a tuple (a named tuple too) and a frozenset are rebuilt as the same type around their redacted items.
  • Other objects are left alone — numbers, None, a read-only mapping, an arbitrary object. Nothing is rendered with str, so nothing changes type; a secret held only inside such an object is not reached.

Keys are never rewritten, only tested with :meth:is_sensitive_key (str(key) for a non-string key, so b"authorization" is sensitive too).

Parameters:

Name Type Description Default
value T

The structure to redact.

required

Returns:

Name Type Description
T T

value itself for a mutable container, the redacted copy

T

for a str, bytes, tuple or frozenset, and

T

value unchanged for anything else.

Examples:

>>> event = {"vars": {"headers": [(b"authorization", b"Bearer abc")]}}
>>> RedactionPolicy().redact_in_place(event) is event
True
>>> event["vars"]["headers"]
[(b'authorization', b'[REDACTED]')]

RedactionFilter

RedactionFilter(policy: RedactionPolicy | None = None)

Bases: Filter

Redact a log record in place before any formatter renders it.

Attach it to a handler, not a logger: a logger's filters do not run for records propagated from its children, a handler's do. :func:tempest_fastapi_sdk.configure_logging does that for every handler it installs when redact is set; attach it yourself to any handler you add on top (Sentry, a syslog sink).

What it rewrites:

  • msg / args — the message is rendered, redacted, and stored back as msg with args cleared, so the original arguments do not reach the formatter. A mapping argument has its sensitive keys replaced before rendering.
  • exc_text — the traceback is rendered from exc_info (unless a previous step already did) and redacted. Both the stdlib formatter and :class:~tempest_fastapi_sdk.JSONFormatter prefer exc_text over re-rendering exc_info.
  • stack_info — redacted as text.
  • every extra= field — sensitive keys replaced whole, other values through :meth:RedactionPolicy.redact_value.

The record is marked once redacted by a given policy, so the several handlers :func:~tempest_fastapi_sdk.configure_logging installs pay for it once per record. The filter never drops a record.

Attributes:

Name Type Description
policy RedactionPolicy

What to redact.

Initialize the filter.

Parameters:

Name Type Description Default
policy RedactionPolicy | None

What to redact. None uses RedactionPolicy() — the default keys and patterns.

None

filter

filter(record: LogRecord) -> bool

Redact record in place.

A message whose arguments do not match its format string is not rendered here (that error belongs to the handler, which reports it through handleError); its template and arguments are redacted separately instead, so the error report does not leak them either.

Parameters:

Name Type Description Default
record LogRecord

The record to redact.

required

Returns:

Name Type Description
bool bool

Always True — redaction never suppresses a record.

REDACTED module-attribute

REDACTED: str = '[REDACTED]'

The default text that replaces every redacted value.

DEFAULT_REDACT_KEYS module-attribute

DEFAULT_REDACT_KEYS: frozenset[str] = frozenset(
    {
        "api_key",
        "apikey",
        "authorization",
        "cookie",
        "credential",
        "email",
        "otp",
        "passwd",
        "password",
        "private_key",
        "secret",
        "signature",
        "token",
        "verification_code",
    }
)

Key fragments whose value is always redacted.

Matching is by substring on the key normalized to lower case with - turned into _, so access_token, X-API-Key, Set-Cookie and client_secret all match. Substring matching errs on the side of hiding: email_verified and token_type are redacted too, which costs a field's readability and never leaks one.

Substring is right for an unambiguous name (password). A short, common name such as code or pin would hide status_code and country_code as well, so it goes in :attr:RedactionPolicy.exact_keys, compared by equality, instead.

DEFAULT_REDACT_PATTERNS module-attribute

DEFAULT_REDACT_PATTERNS: tuple[Pattern[str], ...] = (
    JWT_PATTERN,
    BEARER_PATTERN,
    EMAIL_PATTERN,
    CAPABILITY_PATH_PATTERN,
)

The patterns redacted from free text by default, in application order.

EMAIL_PATTERN module-attribute

EMAIL_PATTERN: Pattern[str] = re.compile(
    "[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\\.[A-Za-z0-9-]+)*\\.[A-Za-z]{2,}"
)

An e-mail address anywhere in a string.

BEARER_PATTERN module-attribute

BEARER_PATTERN: Pattern[str] = re.compile(
    "\\bBearer\\s+[A-Za-z0-9\\-._~+/]+=*", re.IGNORECASE
)

A Bearer <credential> pair, the shape of an Authorization header.

JWT_PATTERN module-attribute

JWT_PATTERN: Pattern[str] = re.compile(
    "\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]*"
)

A compact JWS — three base64url segments, the header starting eyJ.

The signature segment may be empty, which is what an alg: none token looks like.

CAPABILITY_PATH_PATTERN module-attribute

CAPABILITY_PATH_PATTERN: Pattern[str] = re.compile(
    "(?:"
    + "|".join(f"(?<=/{segment}/)" for segment in CAPABILITY_PATH_SEGMENTS)
    + ")(?!(?:request|confirm)(?:[/?#\\s]|$))[^/?#\\s\\\"']+"
)

The token segment of a :data:CAPABILITY_PATH_SEGMENTS URL.

Only the segment itself matches, so /auth/password-reset/<token> reads /auth/password-reset/[REDACTED] and the route stays visible. The literal sibling routes (/password-reset/request, /email-change/confirm) are not tokens and are left alone.

CAPABILITY_PATH_SEGMENTS module-attribute

CAPABILITY_PATH_SEGMENTS: tuple[str, ...] = (
    "activate",
    "email-change",
    "email-verify",
    "password-reset",
)

Path segments under which the SDK's own routes take a token in the URL.

make_auth_router mounts /activate/{token}, /password-reset/{token}, /email-change/{token} and /email-verify/{token}, and make_auth_pages_router mounts /activate/{token}. The segment after each is a live, single-use credential: whoever reads it can redeem it.

CAPABILITY_QUERY_PATTERN module-attribute

CAPABILITY_QUERY_PATTERN: Pattern[str] = re.compile(
    "(?:^|(?<=[?&]))(?P<key>[\\w.-]*(?:token|signature)=)[^&#]*", re.IGNORECASE
)

A signature= or *token= parameter of a query string.

Covers the signature that :func:~tempest_fastapi_sdk.sign_url appends and the ?token= the default activation and reset link templates carry.

redact_capability_url

redact_capability_url(value: str, *, replacement: str = REDACTED) -> str

Hide the credentials the SDK itself puts in URLs.

Replaces the token segment of every :data:CAPABILITY_PATH_SEGMENTS route and the value of every signature= / *token= query parameter. Apply it separately to a path and to a query string, which is what :class:~tempest_fastapi_sdk.AccessLogMiddleware does by default.

Parameters:

Name Type Description Default
value str

A request path, or a raw query string (no leading ? needed).

required
replacement str

What a hidden value is written as.

REDACTED

Returns:

Name Type Description
str str

value with those credentials replaced.

Examples:

>>> redact_capability_url("/auth/password-reset/abc123")
'/auth/password-reset/[REDACTED]'
>>> redact_capability_url("expires=60&signature=deadbeef")
'expires=60&signature=[REDACTED]'

SECRET_KEY_PATTERN module-attribute

SECRET_KEY_PATTERN: Pattern[str] = re.compile(
    "\\b(?:sk|rk)_(?:live_|test_)?[A-Za-z0-9]{8,}"
)

A third-party secret API key written sk_... / rk_....

Covers the RevenueCat secret key (sk_ and eight or more alphanumerics) and the Stripe secret and restricted keys (sk_live_, sk_test_, rk_live_, rk_test_). Not part of :data:DEFAULT_REDACT_PATTERNS; :func:~tempest_fastapi_sdk.make_sentry_before_send adds it to its default policy, and a log policy opts in with extra_patterns.

make_sentry_before_send

make_sentry_before_send(policy: RedactionPolicy | None = None) -> SentryBeforeSend

Build a Sentry before_send that redacts credentials by value.

Every string of the event — exception messages, breadcrumb messages, frame vars at any depth, request data — goes through policy's text patterns and key=value rule, and every mapping key policy deems sensitive has its value replaced, all through :meth:RedactionPolicy.redact_in_place: no depth limit, the event mutated where it stands, tuples and bytes kept as such. The top-level :data:SENTRY_META_KEY annotations are skipped.

Pass it as sentry_sdk.init(before_send=make_sentry_before_send()). It runs after Sentry's own scrubber and adds to it; it does not replace it.

Parameters:

Name Type Description Default
policy RedactionPolicy | None

What to redact. None uses the default keys and patterns (e-mail, Bearer, JWT, the SDK's capability URLs) plus :data:SECRET_KEY_PATTERN, written as :data:SENTRY_FILTERED.

None

Returns:

Name Type Description
SentryBeforeSend SentryBeforeSend

The callback. It returns the event it was given,

SentryBeforeSend

never None.

Examples:

>>> before_send = make_sentry_before_send()
>>> event = {"message": "Authorization: Bearer abc123"}
>>> before_send(event, {})["message"]
'Authorization: [Filtered]'

SentryBeforeSend

Bases: Protocol

What :func:make_sentry_before_send returns.

Generic in the event type, so it is accepted wherever sentry_sdk expects Callable[[Event, Hint], Event | None]: the event comes back as the same object and the same type, never None — redaction does not drop events.

SENTRY_FILTERED module-attribute

SENTRY_FILTERED: Final[str] = '[Filtered]'

The marker the default Sentry policy writes in place of a secret.

It is the text Sentry's own EventScrubber writes, so a value hidden by key name and one hidden by value read the same in the Sentry UI.

SENTRY_META_KEY module-attribute

SENTRY_META_KEY: Final[str] = '_meta'

The top-level event key :func:make_sentry_before_send leaves alone.

sentry-sdk 2.x puts its annotations there, keyed by the path of the annotated value: a truncated frame variable named token yields _meta.exception.values.0.stacktrace.frames.1.vars.token holding {"": {"rem": [...]}}. It carries no event data, and redacting it by key would turn that annotation into a string.

DEFAULT_ALERT_MAX_PER_WINDOW module-attribute

DEFAULT_ALERT_MAX_PER_WINDOW: Final[int] = 20

Deliveries allowed per source (API, app) across its fingerprints in one window.

DEFAULT_ALERT_SUBJECT_PREFIX module-attribute

DEFAULT_ALERT_SUBJECT_PREFIX: Final[str] = '[ALERT]'

What every alert subject starts with, so a mail filter can route it.

DEFAULT_ALERT_WINDOW_SECONDS module-attribute

DEFAULT_ALERT_WINDOW_SECONDS: Final[int] = 900

How long one fingerprint stays silenced after a delivery: 15 minutes.

clear_request_id

clear_request_id(token: Token[str | None]) -> None

Reset the request ID using the token returned by :func:set_request_id.

Parameters:

Name Type Description Default
token Token[str | None]

The token obtained from a previous :func:set_request_id call.

required

get_request_id

get_request_id() -> str | None

Return the current request ID, or None outside a request.

Returns:

Type Description
str | None

str | None: The active correlation ID, or None when not set.

request_id_ctx module-attribute

request_id_ctx: ContextVar[str | None] = ContextVar('tempest_request_id', default=None)

Per-request correlation identifier.

Set by :class:tempest_fastapi_sdk.api.middlewares.RequestIDMiddleware on every inbound HTTP request, consumed by :class:tempest_fastapi_sdk.core.logging.JSONFormatter so every log line carries the originating request ID.

set_request_id

set_request_id(value: str) -> Token[str | None]

Bind a request ID for the current async context.

Parameters:

Name Type Description Default
value str

The correlation identifier to set.

required

Returns:

Type Description
Token[str | None]

Token[str | None]: A token that can be passed to

Token[str | None]

func:clear_request_id to restore the previous value.

BaseIntEnum

Bases: _EnumHelpers, int, Enum

Base class for integer-valued enums.

Mixing in int makes every member a genuine integer instance, so members compare equal to their values (Member == 1), serialize cleanly outside Pydantic, and bind directly to Integer database columns as their value.

Note

As with :class:BaseStrEnum, str(member) and f"{member}" render the value ("2"), not "Priority.HIGH", and numeric format specs keep working (f"{Priority.HIGH:03d}" -> "002").

BaseStrEnum

Bases: _EnumHelpers, str, Enum

Base class for string-valued enums.

Mixing in str makes every member a genuine string instance, so members compare equal to their values (Member == "VALUE"), serialize cleanly outside Pydantic, and bind directly to String database columns as their value.

Note

Deliberately a str + Enum mixin rather than :class:enum.StrEnum, which is only available from Python 3.11 and would not carry the shared helpers. Text conversion, however, matches StrEnum: str(member) and f"{member}" both render the bare value ("paid"), never "OrderStatus.PAID" — see :meth:_EnumHelpers.__str__.

LocaleEnum

Bases: BaseStrEnum

BCP-47 locale tags (language-REGION) as a string enum.

A canonical, dependency-free list of the locales apps commonly target, so a service never hard-codes a bare "pt-BR" string again. Each member's value is the BCP-47 tag itself, so members compare equal to and bind to a String column as that tag (e.g. LocaleEnum.PT_BR == "pt-BR").

Pair it with :class:tempest_fastapi_sdk.LocaleColumnMixin to add a locale column to a model, and with :class:tempest_fastapi_sdk.MessageCatalog to resolve localized text.

Note

This is a pragmatic, extensible set of widely used locales — not an exhaustive registry of every BCP-47 tag. A project needing a tag not listed here can store the raw string (the column is a plain str); add the member upstream when it becomes common.

normalize_locale_tag

normalize_locale_tag(value: str | LocaleEnum) -> LocaleEnum

Coerce a loose locale string into a :class:LocaleEnum member.

Accepts any case and either separator — "pt_BR", "PT-BR", "pt-br" all resolve to :attr:LocaleEnum.PT_BR — and the bare primary subtag ("pt" -> PT_BR, "en" -> EN_US; the first member declared for that subtag wins). This is the normalizer behind :data:tempest_fastapi_sdk.LocaleField, mirroring normalize_uf for UFField.

Parameters:

Name Type Description Default
value str | LocaleEnum

The raw locale value; a :class:LocaleEnum is returned unchanged.

required

Returns:

Name Type Description
LocaleEnum LocaleEnum

The matching member.

Raises:

Type Description
ValueError

If value matches no supported locale.

configure_logging

configure_logging(
    level: str | int = "INFO",
    *,
    json_output: bool = True,
    logger_name: str | None = None,
    log_dir: str | Path | None = "logs",
    stdout: bool = True,
    file_output: bool = True,
    max_bytes: int = DEFAULT_LOG_MAX_BYTES,
    backup_count: int = DEFAULT_LOG_BACKUP_COUNT,
    rotate_when: str | None = None,
    rotate_interval: int = 1,
    redact: bool | RedactionPolicy = False,
) -> Logger

Install a structured stdout handler on the root (or named) logger.

Replaces existing handlers on the target logger so this can be called safely from create_app without stacking duplicates.

Default behavior (no extra kwargs): emits to both stdout and a logs/ directory next to the service root, one file per level plus a dedicated 500.log:

  • debug.log / info.log / warning.log / error.log / critical.log — each receives only its own level (exact match), so every severity has an isolated, greppable stream.
  • 500.log — only uncaught-500 records (flagged by the catch-all exception handler) so grave failures are never buried among the rest. A 500 therefore appears in both error.log and 500.log.

File handlers always emit JSON regardless of json_output so the :func:tempest_fastapi_sdk.make_logs_router endpoint can parse them.

Parameters:

Name Type Description Default
level str | int

The minimum level to emit (e.g. "INFO", logging.DEBUG).

'INFO'
json_output bool

When True (default), emit JSON via :class:JSONFormatter to stdout. When False, fall back to a human-readable text formatter — useful in local dev where JSON noise overwhelms the terminal. Only affects stdout; files are always JSON.

True
logger_name str | None

The logger to configure. None (default) configures the root logger.

None
log_dir str | Path | None

Directory for per-level + 500.log files. Defaults to "logs" so file logging works out of the box. Pass None or an empty string to disable file logging (equivalent to file_output=False). Ignored when file_output=False.

'logs'
stdout bool

When True (default), attach the stdout handler. Pass False to suppress terminal output entirely (e.g. when a sidecar collects logs from disk).

True
file_output bool

When True (default), attach the per-level + 500.log file handlers under log_dir. Pass False to disable file logging — useful in ephemeral environments (tests, serverless) where the filesystem is read-only or short-lived.

True
max_bytes int

Size at which each file rotates, ~10 MB by default. 0 turns rotation off, leaving plain FileHandlers for a host where logrotate or a sidecar owns retention. Rotating by default is the safe end of that choice: the service that never thought about log growth is exactly the one that fills the disk.

DEFAULT_LOG_MAX_BYTES
backup_count int

Rotated files kept per level (default 5, so roughly 60 MB per level at the default size). Under time-based rotation it is the number of past periods kept: rotate_when="midnight" with backup_count=7 keeps the current day plus the seven before it.

DEFAULT_LOG_BACKUP_COUNT
rotate_when str | None

Rotate by time instead of size. One of :data:LOG_ROTATE_WHEN_CHOICES, case-insensitive ("midnight", "H", "D", "W0"...). When set, every file handler is a :class:~logging.handlers.TimedRotatingFileHandler with utc=True and max_bytes is ignored — a file is never cut by size, so a burst of logging inside one period grows that period's file. Rotated files are named with the period's UTC start (info.log.2026-10-20, or info.log.2026-10-20_13 for "H") and are read by :func:~tempest_fastapi_sdk.read_log_entries like info.log.1 is. None or "" (default) keeps size-based rotation.

None
rotate_interval int

How many rotate_when units make one period (default 1). Must be at least 1.

1
redact bool | RedactionPolicy

When truthy, attach a :class:~tempest_fastapi_sdk.RedactionFilter to every handler installed here — on the handler and not on the logger, because a logger's filters do not run for records propagated from its children. True uses RedactionPolicy(); pass a :class:~tempest_fastapi_sdk.RedactionPolicy to add domain keys or patterns. False (default) installs no filter and leaves records untouched. Redaction rewrites the record in place (msg becomes the rendered, redacted message and args is cleared), so a handler added later on the same logger sees the redacted record too — provided one of these handlers ran first.

False

File logging is best-effort: if log_dir cannot be created or its files cannot be opened (read-only mount, missing write permission, etc.), the file handlers are skipped, a warning is emitted, and the application keeps running with stdout logging — it does not crash at startup. Pass file_output=False to opt out of file logging explicitly when you know the filesystem is unusable.

Returns:

Type Description
Logger

logging.Logger: The configured logger instance.

Raises:

Type Description
ValueError

When both stdout=False and file_output=False are passed — that would silence every handler and leave the application blind, which is almost always a mistake. Also when rotate_when is not an accepted unit or rotate_interval is below 1; both are checked before any existing handler is removed.

Notes

Existing handlers are closed before being removed, not just detached. This runs once per application boot and once per test that wants a clean state, and FileHandler / RotatingFileHandler hold a file descriptor each — without the close they would accumulate across calls.

File logging is best-effort. A read-only or non-writable filesystem is normal in hardened containers, serverless runtimes and CI, and must never crash the application at startup, so the failure degrades to stdout-only and the reason is surfaced once for an operator who did want files. When there is no stdout handler to carry that warning, it goes straight to stderr rather than being swallowed.

DEFAULT_LOG_BACKUP_COUNT module-attribute

DEFAULT_LOG_BACKUP_COUNT: int = 5

Rotated files kept per level.

Five rotated files plus the one being written is roughly 60 MB per level at the default :data:DEFAULT_LOG_MAX_BYTES.

DEFAULT_LOG_MAX_BYTES module-attribute

DEFAULT_LOG_MAX_BYTES: int = 10000000

Size at which each log file rotates — about 10 MB.

Rotation is on by default because the alternative is an outage: the per-level files never stop growing, and on a service that logs a line per request info.log fills the host's disk. 0 opts out, for a host where logrotate or a sidecar already owns the ceiling.

HTTP_500_MARKER module-attribute

HTTP_500_MARKER: str = 'http_500'

extra key the 500 catch-all handler sets so grave failures can be routed to a dedicated 500.log file. See :func:tempest_fastapi_sdk.api.handlers.make_unhandled_exception_handler.

JSONFormatter

Bases: Formatter

Render every log record as a single-line JSON object.

Standard LogRecord fields are mapped to timestamp, level, logger and message. The current request ID (when present) is attached as request_id. When OpenTelemetry is active and a valid recording span is in scope, lowercase hex trace_id (32 hex chars) and span_id (16 hex chars) are attached automatically; otherwise both keys are omitted with zero overhead. Any additional keyword passed to the logger via extra={...} becomes a top-level key in the JSON payload.

The exception key comes from record.exc_text when a previous step already rendered it — the same precedence the stdlib :class:logging.Formatter uses — and from exc_info only otherwise. That is what lets a handler filter such as :class:~tempest_fastapi_sdk.RedactionFilter redact the traceback: rendering exc_info again would write the original text back over the redacted one.

format

format(record: LogRecord) -> str

Serialize record to JSON.

Parameters:

Name Type Description Default
record LogRecord

The record to format.

required

Returns:

Name Type Description
str str

A JSON document as a single line.

LOG_ROTATE_WHEN_CHOICES module-attribute

LOG_ROTATE_WHEN_CHOICES: frozenset[str] = frozenset(
    {"S", "M", "H", "D", "MIDNIGHT", *(f"W{day}" for day in range(7))}
)

Every when that :class:logging.handlers.TimedRotatingFileHandler accepts.

Ported from the branches of TimedRotatingFileHandler.__init__ in the CPython standard library (read on 3.13): S, M, H, D, MIDNIGHT and W0-W6 (W0 is Monday), compared after when.upper(). Anything else makes the handler raise ValueError — but only when the handler is built, which is after :func:configure_logging has already removed the previous handlers, so the check runs here first.

validate_rotate_when

validate_rotate_when(when: str) -> str

Check a time-rotation when before any handler is built.

The standard library validates when only inside TimedRotatingFileHandler.__init__. :func:configure_logging removes the logger's current handlers before it opens new ones, so a typo caught that late would leave the process with no file handlers and a traceback in the middle of boot. Validating first keeps the failure at the call, with the accepted values in the message.

Parameters:

Name Type Description Default
when str

The rotation unit, case-insensitive — one of :data:LOG_ROTATE_WHEN_CHOICES ("midnight", "H", "W0", ...).

required

Returns:

Name Type Description
str str

when unchanged, so the handler sees what the caller

str

wrote.

Raises:

Type Description
ValueError

When when is not one of the accepted values.

DEFAULT_TIMING_LOGGER module-attribute

DEFAULT_TIMING_LOGGER: Final[str] = 'tempest.timing'

Default logger name used by :func:timed and :func:instrument_layer.

timed

timed(
    layer: str,
    op: str | None = None,
    *,
    threshold_ms: float = 0.0,
    level: int = INFO,
    error_level: int = ERROR,
    logger_name: str = DEFAULT_TIMING_LOGGER,
) -> Callable[[F], F]

Time a synchronous or asynchronous function and emit structured telemetry.

On every invocation, the wrapper:

  1. Opens an OpenTelemetry span named "<layer>.<op>" with attributes tempest.layer and tempest.op when the [otel] extra is installed (zero-overhead no-op otherwise).
  2. Measures wall-clock duration using :func:time.perf_counter.
  3. Adds the duration to the active per-request accumulator (if any) via :func:record_layer_timing.
  4. Emits a structured log record carrying layer, op, duration_ms, and outcome ("ok" or "error", plus error on failure). Under :class:~tempest_fastapi_sdk.core.logging.JSONFormatter, the active request_id, trace_id, and span_id are attached automatically because the log record is emitted before the span exits.

Parameters:

Name Type Description Default
layer str

Architectural layer name (e.g. "controller", "service", "repository", "external").

required
op str | None

Operation identifier. Defaults to the wrapped callable's __qualname__.

None
threshold_ms float

Minimum duration in milliseconds before a successful call emits a log line. Defaults to 0.0 (log every call). Failing calls are always logged regardless of threshold.

0.0
level int

Logging level for successful calls. Defaults to :data:logging.INFO.

INFO
error_level int

Logging level for failed calls. Defaults to :data:logging.ERROR.

ERROR
logger_name str

Logger name receiving timing records. Defaults to :data:DEFAULT_TIMING_LOGGER ("tempest.timing").

DEFAULT_TIMING_LOGGER

Returns:

Type Description
Callable[[F], F]

Callable[[F], F]: Decorator preserving the wrapped callable's exact

Callable[[F], F]

static type signature.

Raises:

Type Description
ValueError

When layer is empty or threshold_ms is negative.

instrument_layer

instrument_layer(
    layer: str,
    *,
    threshold_ms: float = 0.0,
    level: int = INFO,
    error_level: int = ERROR,
    logger_name: str = DEFAULT_TIMING_LOGGER,
    include_sync: bool = False,
    exclude: Iterable[str] = (),
) -> Callable[[ClsT], ClsT]

Class decorator applying :func:timed to public methods of a layer class.

Walks cls.__mro__ so both methods declared directly on cls and public CRUD methods inherited from :class:~tempest_fastapi_sdk.controllers.base.BaseController, :class:~tempest_fastapi_sdk.services.base.BaseService, or :class:~tempest_fastapi_sdk.db.repository.BaseRepository are timed under op="<ClassName>.<method>". Base classes are never mutated.

Safety guarantees:

  • Private and dunder attributes (leading _) are skipped.
  • Methods already decorated with :func:timed keep their explicit configuration and are never double-wrapped.
  • @property and non-function descriptors (such as cached_property or SQLAlchemy column descriptors) are left untouched.
  • @classmethod and @staticmethod wrappers are preserved after timing their underlying function.
  • Generator and async-generator functions are skipped so lazy iteration semantics are never altered.

Parameters:

Name Type Description Default
layer str

Architectural layer name (e.g. "controller", "service", "repository").

required
threshold_ms float

Minimum duration in milliseconds before a successful call emits a log line. Defaults to 0.0.

0.0
level int

Logging level for successful calls. Defaults to :data:logging.INFO.

INFO
error_level int

Logging level for failed calls. Defaults to :data:logging.ERROR.

ERROR
logger_name str

Logger name receiving timing records. Defaults to :data:DEFAULT_TIMING_LOGGER.

DEFAULT_TIMING_LOGGER
include_sync bool

When False (default), only async def public methods are wrapped — avoiding noise on lightweight sync helpers such as BaseRepository.map_to_response. Set True to instrument synchronous public methods too.

False
exclude Iterable[str]

Method names to skip explicitly.

()

Returns:

Type Description
Callable[[ClsT], ClsT]

Callable[[ClsT], ClsT]: Class decorator returning the instrumented

Callable[[ClsT], ClsT]

class with its static type preserved.

Raises:

Type Description
ValueError

When layer is empty or threshold_ms is negative.

layer_timings_ctx module-attribute

layer_timings_ctx: ContextVar[dict[str, float] | None] = ContextVar(
    "tempest_layer_timings", default=None
)

Per-request mapping from layer name to accumulated wall-clock milliseconds.

Bound per request by :class:~tempest_fastapi_sdk.api.middlewares.access_log.AccessLogMiddleware via :func:start_layer_timings and populated by :func:timed / :func:record_layer_timing. None outside an active timing scope.

start_layer_timings

start_layer_timings() -> Token[dict[str, float] | None]

Bind a fresh per-request layer timing accumulator for the current context.

Returns:

Type Description
Token[dict[str, float] | None]

Token[dict[str, float] | None]: A token to pass to

Token[dict[str, float] | None]

func:clear_layer_timings in a finally block.

record_layer_timing

record_layer_timing(layer: str, duration_ms: float) -> None

Add duration_ms to layer in the active request accumulator.

Does nothing when no accumulator is bound (outside a request, or when AccessLogMiddleware was not built with include_layer_timings=True).

Parameters:

Name Type Description Default
layer str

Architectural layer name (e.g. "controller", "service", "repository").

required
duration_ms float

Elapsed wall-clock time in milliseconds to add.

required

get_layer_timings

get_layer_timings() -> dict[str, float] | None

Return a snapshot of the active layer timing accumulator.

Returns:

Type Description
dict[str, float] | None

dict[str, float] | None: A shallow copy mapping each recorded layer

dict[str, float] | None

name to its accumulated duration in milliseconds, or None when no

dict[str, float] | None

accumulator is bound in the current async context.

clear_layer_timings

clear_layer_timings(token: Token[dict[str, float] | None]) -> None

Restore the previous layer timing accumulator using token.

Parameters:

Name Type Description Default
token Token[dict[str, float] | None]

The token returned by :func:start_layer_timings.

required