Skip to content

Home > @opengovsg/logging

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 ​

FunctionDescription
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:

ts
// 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.

| | [serializeError(err)](./logging.serializeerror.md) |

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 ​

InterfaceDescription
AccessDeniedInputInput for FailuresAudit.accessDenied().
AccountCreatedInputInput for UserManagementAudit.accountCreated().
AccountDeactivatedInputInput for UserManagementAudit.accountDeactivated().
AccountDeletedInputInput for UserManagementAudit.accountDeleted().
AccountModifiedInputInput for UserManagementAudit.accountModified().
ApiKeyChangedInputInput for UserManagementAudit.apiKeyChanged().
ApiUsageAudit

API usage audit events (category apiUsage).

Covers API token lifecycle and access to sensitive endpoints. These run on machine/bearer-token requests that often have no authenticated user, so userId is optional throughout — supply it only when the token is user-bound. Anomaly/abuse detection is intentionally absent — the app does not know a call is anomalous at log time; that is a sink/SIEM concern *over* these lines (ADR-0007).

AuditInputBaseFields every audit input accepts in addition to its event-specific shape.
AuditLogger

The fixed-shape **audit** helper layer — logger.audit.<category>.<event>(…).

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 audit, category, and event.

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.

AuthnAuditAuthentication & session audit events (category authn).
BasicLoggerA simplified logger interface that both console and Logger can implement, for shared client and server side code.
BulkExportedInputInput for DataAccessAudit.bulkExported().
ConfigChangeAudit

Application function & security-configuration change audit events (category configChange). Includes the org-level policy changes deferred from userManagement (password/access policy, ACLs, retention, logging).

Admin actions, downstream of auth: actor user_id and client_ip are scope-read. Log *what* changed (and old/new values when non-sensitive), never secrets.

CreateLoggerA 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 dataAccess).

Downstream of authentication: the acting user_id and client_ip are scope-read. Log *what* was accessed — resource type/id, classification — never the data itself.

DataAccessedInputInput for DataAccessAudit.dataAccessed().
FailuresAuditSecurity 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.

LoggerOptionsPer-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.
LoggingConfigDeployment config passed to createLogging(). The core reads no environment variables of its own — the consuming app injects these.
LoginFailedInputInput for AuthnAudit.loginFailed().
LogInput

The shape of a single log call: a message, an optional action naming the operation, and optional structured context, error, and merged fields.

action is a single, optional string naming the current operation. Scoping (Logger.scope() / Logger.setAction()) sets the leaf action; the per-call action wins over it. Only that most-specific action is emitted.

LoginSucceededInputInput for AuthnAudit.loginSucceeded().
MfaSettingChangedInputInput for UserManagementAudit.mfaSettingChanged().
OwnershipTransferredInputInput for ResourceAudit.ownershipTransferred().
PasswordResetInputInput for UserManagementAudit.passwordReset().
PolicyChangedInputInput for ConfigChangeAudit.policyChanged().
PrivilegeEscalationDeniedInputInput for FailuresAudit.privilegeEscalationDenied().
RecordDownloadedInputInput for DataAccessAudit.recordDownloaded().
ResourceAudit

Resource/entity lifecycle audit events (category resource).

The **mutation** side of generic business entities (forms, projects, documents, …) — complements dataAccess (the read/export side) and userManagement (accounts specifically). Downstream of auth: the actor (user_id) and client_ip are scope-read. Log the resource type/id and *what* changed (field names), never the contents.

ResourceCreatedInputInput for ResourceAudit.created().
ResourceDeletedInputInput for ResourceAudit.deleted().
ResourceUpdatedInputInput for ResourceAudit.updated().
RoleChangedInputInput for UserManagementAudit.roleChanged().
SecurityConfigChangedInputInput for ConfigChangeAudit.securityConfigChanged().
SensitiveActionBlockedInputInput for FailuresAudit.sensitiveActionBlocked().
SensitiveEndpointAccessedInputInput for ApiUsageAudit.sensitiveEndpointAccessed().
SessionCreatedInputInput for AuthnAudit.sessionCreated().
SessionTerminatedInputInput for AuthnAudit.sessionTerminated().
SessionTimedOutInputInput for AuthnAudit.sessionTimedOut().
SystemLoggerOptionsMetadata 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.
TokenInvalidatedInputInput for ApiUsageAudit.tokenInvalidated().
TokenIssuedInputInput for ApiUsageAudit.tokenIssued().
TokenRefreshedInputInput for ApiUsageAudit.tokenRefreshed().
TokenReusedInputInput for AuthnAudit.tokenReused().
UserManagementAudit

User & permission management audit events (category userManagement).

These act on a *target* account that is usually distinct from the *actor*: the actor is the authenticated request's user_id (read from scope), the target is targetUserId in the payload (emitted as context.target_user_id). They coincide only for self-service actions (self-signup, self password reset).

Events log *what changed*, never the changed values — field/role names and id references only — so secrets and PII stay unrepresentable.

WithLoggerA mixin shape for objects that carry a Logger on a logger field.

Type Aliases ​

Type AliasDescription
AuditContextFree-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.
LogLevelSeverity levels this logger emits, ordered by RFC 5424 (syslog). silent disables all output.