logging package
A framework-agnostic structured logging core built on pino. It standardises a flat, Datadog-aligned newline-delimited JSON wire schema with custom syslog levels, scoped loggers that accumulate an action path, contextual metadata, an oversized-context guard, and pluggable error serialisation (a framework-neutral default, overridable via LoggingConfig.serializeError).
Call createLogging() once at boot with your deployment identity, then create request-scoped loggers from the returned CreateLogger.
Functions
| Function | Description |
|---|---|
| createLogging(config) | Build a CreateLogger bound to a fixed deployment config. Call once at process boot with values mapped from your app's own environment, and re-export the result so call sites can create request-scoped loggers: |
// src/logger.ts — owned by the app
export const createBaseLogger = createLogging({ env, service, version })The returned factory is immutable: config is fixed at creation and the pino instance is built once. To run with different config, create another factory.
env, service, and version are required — deployment identity must be explicit. level (default info) and pretty (default false) are optional. Never throws.
The default error serialiser: shapes an already-normalised Error into the flat object emitted as the error wire field. Framework-neutral — it reads no framework-specific fields (e.g. it does \*\*not\*\* map a tRPC code to kind).
Produces { ...ownEnumerableProps, kind, message, stack, cause }: - kind – the error's class name (err.name), Datadog's error.kind facet. - message / stack / cause – the native fields (non-enumerable, so added explicitly rather than via the spread). - any own enumerable properties the error carries (e.g. a tRPC code) survive on the wire under error, just not lifted into kind.
Override via [LoggingConfig.serializeError](./logging.loggingconfig.serializeerror.md) to add framework-specific shaping (e.g. tRPC code → kind, NestJS HttpException).
Interfaces
| Interface | Description |
|---|---|
| AccessDeniedInput | Input for FailuresAudit.accessDenied(). |
| AccountCreatedInput | Input for UserManagementAudit.accountCreated(). |
| AccountDeactivatedInput | Input for UserManagementAudit.accountDeactivated(). |
| AccountDeletedInput | Input for UserManagementAudit.accountDeleted(). |
| AccountModifiedInput | Input for UserManagementAudit.accountModified(). |
| ApiKeyChangedInput | Input for UserManagementAudit.apiKeyChanged(). |
| ApiUsageAudit | API usage audit events (category Covers API token lifecycle and access to sensitive endpoints. These run on machine/bearer-token requests that often have no authenticated user, so |
| AuditInputBase | Fields every audit input accepts in addition to its event-specific shape. |
| AuditLogger | The fixed-shape **audit** helper layer — Each method records one auditable business event from a closed, governed taxonomy (ADR-0007). Unlike the free-form base logger, every event has a *fixed, type-enforced shape*: required fields are mandatory at compile time, shared identity is read from the bound scope, and the helper stamps the Controlled wire fields The helper performs **no value transformation**: secrets are kept out *by shape* (they are never fields) and PII is left to the sink. See ADR-0007. |
| AuthnAudit | Authentication & session audit events (category authn). |
| BasicLogger | A simplified logger interface that both console and Logger can implement, for shared client and server side code. |
| BulkExportedInput | Input for DataAccessAudit.bulkExported(). |
| ConfigChangeAudit | Application function & security-configuration change audit events (category Admin actions, downstream of auth: actor |
| CreateLogger | A Logger factory bound to a fixed LoggingConfig, returned by createLogging(). Call it directly for a **request** logger (client identity required via LoggerOptions); call .system(...) for a **request-less** logger (startup, jobs, cron — SystemLoggerOptions). |
| DataAccessAudit | Data access, movement & export audit events (category Downstream of authentication: the acting |
| DataAccessedInput | Input for DataAccessAudit.dataAccessed(). |
| FailuresAudit | Security failure audit events (category failures) — *handled*, security- relevant denials, so they fire at warn (the control worked). Application *errors* go through the base error(); anomaly/abuse detection is a sink concern (ADR-0007). |
| Logger | Structured logger with action scoping, contextual metadata, and severity levels aligned to RFC 5424 (syslog). ## Choosing a level (the discriminator is *does someone need to act?*) - debug — verbose diagnostics, only while actively debugging. - info — the routine activity trail; no action implied. - notice — significant or **auditable** business events. - warn — something off but handled; no action needed now. - error — an operation failed; a human should investigate. |
| LoggerOptions | Per-request metadata for a request-scoped Logger. Extends SystemLoggerOptions with the request identity every request line should carry. clientIp and userAgent are **required keys** that accept string | null | undefined: the caller must *acknowledge* them — forgetting the key is a compile error — and pass null/undefined explicitly when the value is genuinely absent (e.g. a missing headers.get(...)), rather than leaving it off by accident. traceId is optional: trace correlation comes from dd-trace log injection (see SystemLoggerOptions.traceId). For request-less contexts use SystemLoggerOptions via createLogging(...).system(...), where the client identity does not exist. |
| LoggingConfig | Deployment config passed to createLogging(). The core reads no environment variables of its own — the consuming app injects these. |
| LoginFailedInput | Input for AuthnAudit.loginFailed(). |
| LogInput | The shape of a single log call: a
|
| LoginSucceededInput | Input for AuthnAudit.loginSucceeded(). |
| MfaSettingChangedInput | Input for UserManagementAudit.mfaSettingChanged(). |
| OwnershipTransferredInput | Input for ResourceAudit.ownershipTransferred(). |
| PasswordResetInput | Input for UserManagementAudit.passwordReset(). |
| PolicyChangedInput | Input for ConfigChangeAudit.policyChanged(). |
| PrivilegeEscalationDeniedInput | Input for FailuresAudit.privilegeEscalationDenied(). |
| RecordDownloadedInput | Input for DataAccessAudit.recordDownloaded(). |
| ResourceAudit | Resource/entity lifecycle audit events (category The **mutation** side of generic business entities (forms, projects, documents, …) — complements |
| ResourceCreatedInput | Input for ResourceAudit.created(). |
| ResourceDeletedInput | Input for ResourceAudit.deleted(). |
| ResourceUpdatedInput | Input for ResourceAudit.updated(). |
| RoleChangedInput | Input for UserManagementAudit.roleChanged(). |
| SecurityConfigChangedInput | Input for ConfigChangeAudit.securityConfigChanged(). |
| SensitiveActionBlockedInput | Input for FailuresAudit.sensitiveActionBlocked(). |
| SensitiveEndpointAccessedInput | Input for ApiUsageAudit.sensitiveEndpointAccessed(). |
| SessionCreatedInput | Input for AuthnAudit.sessionCreated(). |
| SessionTerminatedInput | Input for AuthnAudit.sessionTerminated(). |
| SessionTimedOutInput | Input for AuthnAudit.sessionTimedOut(). |
| SystemLoggerOptions | Metadata for a **request-less** ("system") Logger — process startup, background jobs, cron, queue consumers, CLI. These contexts have no client identity, so clientIp / userAgent are absent here; bind a request logger with LoggerOptions instead when handling an HTTP request. |
| TokenInvalidatedInput | Input for ApiUsageAudit.tokenInvalidated(). |
| TokenIssuedInput | Input for ApiUsageAudit.tokenIssued(). |
| TokenRefreshedInput | Input for ApiUsageAudit.tokenRefreshed(). |
| TokenReusedInput | Input for AuthnAudit.tokenReused(). |
| UserManagementAudit | User & permission management audit events (category These act on a *target* account that is usually distinct from the *actor*: the actor is the authenticated request's Events log *what changed*, never the changed values — field/role names and id references only — so secrets and PII stay unrepresentable. |
| WithLogger | A mixin shape for objects that carry a Logger on a logger field. |
Type Aliases
| Type Alias | Description |
|---|---|
| AuditContext | Free-form business fields an audit call may carry in addition to its fixed shape. Merged into the line's context. App-owned; keep keys snake_case. |
| LogLevel | Severity levels this logger emits, ordered by RFC 5424 (syslog). silent disables all output. |