tempest_fastapi_sdk.core¶
Primitivas transversais: tipagem estrita, logging, observabilidade por camada, redação de dados sensíveis e locale da documentação.
strict_types
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
F |
F
|
The wrapped callable with the same signature. Raises |
F
|
class: |
|
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
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
F |
F
|
The wrapped callable with the same signature. Raises |
F
|
class: |
|
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 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 |
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
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
DocsLocale
module-attribute
¶
A language the route-docs catalog carries.
configure_root_once
¶
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: |
{}
|
Returns:
| Type | Description |
|---|---|
Logger
|
logging.Logger: The root logger, configured. |
Raises:
| Type | Description |
|---|---|
TypeError
|
When |
reinitialize_logging
¶
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_keyshas its whole value replaced. The same keys also drive akey=value/key: valuepattern over free text, so?token=abcin 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_patternsreplaced. The defaults cover e-mail addresses,Bearercredentials 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: |
extra_keys |
Collection[str]
|
Additional key fragments, added to
:attr: |
exact_keys |
Collection[str]
|
Keys matched by equality after the
same normalization, for a short name a substring would
over-match: |
patterns |
Sequence[Pattern[str] | str]
|
Base text patterns.
Defaults to :data: |
extra_patterns |
Sequence[Pattern[str] | str]
|
Additional text
patterns, applied after :attr: |
replacement |
str
|
The text written in place of each redacted
value. Defaults to :data: |
is_sensitive_key
¶
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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
redact_text
¶
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: |
|
str
|
pair are kept, so the line still says what was hidden. |
redact_value
¶
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 |
object
|
for a mapping, a |
|
object
|
is never mutated. |
redact_in_place
¶
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
strof 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
setis refilled; abytearrayis rewritten. Each comes back as the same object. - Types kept. A
strgoes through :meth:redact_text;bytesis decoded as UTF-8 withsurrogateescape(so any byte sequence round-trips), redacted and encoded back; atuple(a named tuple too) and afrozensetare 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 withstr, 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
|
|
T
|
for a |
|
T
|
|
Examples:
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 asmsgwithargscleared, 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 fromexc_info(unless a previous step already did) and redacted. Both the stdlib formatter and :class:~tempest_fastapi_sdk.JSONFormatterpreferexc_textover re-renderingexc_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
|
filter
¶
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 |
REDACTED
module-attribute
¶
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
¶
A Bearer <credential> pair, the shape of an Authorization header.
JWT_PATTERN
module-attribute
¶
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
|
required |
replacement
|
str
|
What a hidden value is written as. |
REDACTED
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
Examples:
SECRET_KEY_PATTERN
module-attribute
¶
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
|
Returns:
| Name | Type | Description |
|---|---|---|
SentryBeforeSend |
SentryBeforeSend
|
The callback. It returns the event it was given, |
SentryBeforeSend
|
never |
Examples:
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
¶
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
¶
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
¶
Deliveries allowed per source (API, app) across its fingerprints in one window.
DEFAULT_ALERT_SUBJECT_PREFIX
module-attribute
¶
What every alert subject starts with, so a mail filter can route it.
DEFAULT_ALERT_WINDOW_SECONDS
module-attribute
¶
How long one fingerprint stays silenced after a delivery: 15 minutes.
clear_request_id
¶
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: |
required |
get_request_id
¶
Return the current request ID, or None outside a request.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The active correlation ID, or |
request_id_ctx
module-attribute
¶
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
¶
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: |
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: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
LocaleEnum |
LocaleEnum
|
The matching member. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 botherror.logand500.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'
|
json_output
|
bool
|
When |
True
|
logger_name
|
str | None
|
The logger to configure. |
None
|
log_dir
|
str | Path | None
|
Directory for per-level + |
'logs'
|
stdout
|
bool
|
When |
True
|
file_output
|
bool
|
When |
True
|
max_bytes
|
int
|
Size at which each file rotates, ~10 MB by
default. |
DEFAULT_LOG_MAX_BYTES
|
backup_count
|
int
|
Rotated files kept per level (default |
DEFAULT_LOG_BACKUP_COUNT
|
rotate_when
|
str | None
|
Rotate by time instead of size. One of
:data: |
None
|
rotate_interval
|
int
|
How many |
1
|
redact
|
bool | RedactionPolicy
|
When truthy, attach a
:class: |
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 |
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
¶
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
¶
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
¶
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
¶
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
¶
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: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
wrote. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
DEFAULT_TIMING_LOGGER
module-attribute
¶
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:
- Opens an OpenTelemetry span named
"<layer>.<op>"with attributestempest.layerandtempest.opwhen the[otel]extra is installed (zero-overhead no-op otherwise). - Measures wall-clock duration using :func:
time.perf_counter. - Adds the duration to the active per-request accumulator (if any) via
:func:
record_layer_timing. - Emits a structured log record carrying
layer,op,duration_ms, andoutcome("ok"or"error", pluserroron failure). Under :class:~tempest_fastapi_sdk.core.logging.JSONFormatter, the activerequest_id,trace_id, andspan_idare attached automatically because the log record is emitted before the span exits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer
|
str
|
Architectural layer name (e.g. |
required |
op
|
str | None
|
Operation identifier. Defaults to the wrapped
callable's |
None
|
threshold_ms
|
float
|
Minimum duration in milliseconds before a
successful call emits a log line. Defaults to |
0.0
|
level
|
int
|
Logging level for successful calls. Defaults to
:data: |
INFO
|
error_level
|
int
|
Logging level for failed calls. Defaults to
:data: |
ERROR
|
logger_name
|
str
|
Logger name receiving timing records. Defaults to
:data: |
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 |
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:
timedkeep their explicit configuration and are never double-wrapped. @propertyand non-function descriptors (such ascached_propertyor SQLAlchemy column descriptors) are left untouched.@classmethodand@staticmethodwrappers 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. |
required |
threshold_ms
|
float
|
Minimum duration in milliseconds before a
successful call emits a log line. Defaults to |
0.0
|
level
|
int
|
Logging level for successful calls. Defaults to
:data: |
INFO
|
error_level
|
int
|
Logging level for failed calls. Defaults to
:data: |
ERROR
|
logger_name
|
str
|
Logger name receiving timing records. Defaults to
:data: |
DEFAULT_TIMING_LOGGER
|
include_sync
|
bool
|
When |
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_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
¶
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: |
record_layer_timing
¶
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. |
required |
duration_ms
|
float
|
Elapsed wall-clock time in milliseconds to add. |
required |
get_layer_timings
¶
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 |
dict[str, float] | None
|
accumulator is bound in the current async context. |
clear_layer_timings
¶
Restore the previous layer timing accumulator using token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Token[dict[str, float] | None]
|
The token returned by
:func: |
required |