tabletcommand-logger
v4.0.0
Published
Tablet Command Logging Configuration
Keywords
Readme
tabletcommand-logger
Tablet Command shared logging and metrics library for Node.js services.
Version 4.0.0 uses Pino for structured JSON logging to process.stdout.
Features
- Pino JSON stdout engine: High-performance, low-overhead JSON logging to stdout, ready for container log collection by Datadog Agent.
- Strict Compile-Time Signature Enforcement: Enforces Pino conventions
(obj, msg)or(msg). Legacy Winston-style inverted calls(msg, obj)fail TypeScript compilation with immediate compiler feedback. - Redaction: Every log object, child binding, request body and serialized error is walked once, matching key names without case,
-or_. Credentials (apiKey,authToken,partnerKey, ...) are cut to a 7-character prefix; passwords, secrets, private keys and personal data are masked (<redacted>). - OpenTelemetry Correlation: Built-in mixin automatically detects active OpenTelemetry spans and injects
trace_idandspan_idwithout requiring OpenTelemetry packages as hard dependencies. - Local Dev Pretty Printing: Enables
pino-prettyformatting only when asked for:NODE_ENV=development(outside CI),PINO_PRETTY=true, orpretty: truein the config. Any other environment, including an unsetNODE_ENV, writes NDJSON. - HTTP Middlewares: Provides
loggerMiddleware(backed bypino-http),statusLogger(POST request auditing), andmetricsMiddleware(statsd integration).
Installation
npm install tabletcommand-loggerTo enable OpenTelemetry trace correlation, install @opentelemetry/api in your service:
npm install @opentelemetry/apiTo enable pretty-printed colorized logs in local development, install pino-pretty as a dev dependency:
npm install -D pino-prettyIf omitted, tabletcommand-logger automatically falls back to standard NDJSON stdout without crashing.
Usage
Creating a Logger
import logger, { LoggerConfig } from "tabletcommand-logger";
const config: LoggerConfig = {
name: "server-location",
logToConsole: true,
};
const log = logger(config);Logging Conventions
Pino requires structured metadata objects to be passed as the first argument:
// ✅ Good: Structured object first
log.info({ userId: "123", action: "update" }, "User profile updated");
// ✅ Good: String message only
log.info("Server started on port 3000");
// ✅ Good: Error first
log.error(err, "Failed to connect to database");
// ❌ COMPILE ERROR: String first with object (legacy Winston style)
// TypeScript will reject this call with a compile error:
log.info("User profile updated", { userId: "123" });HTTP Middleware
import express from "express";
import { logger, loggerMiddleware } from "tabletcommand-logger";
const app = express();
const appLogger = logger({ name: "my-service", logToConsole: true });
app.use(loggerMiddleware(appLogger));Redaction Policy
Credentials and secrets are redacted before leaving the process:
- API Keys (
apikey,personnelapikey,signupkey,x-tc-auth-token): Truncated to the first 7 characters (e.g.abcdef1...). - Authorization headers (
Bearer <token>,Basic <cred>): Scheme is preserved and the credential behind it is truncated to 7 characters. Both request (req.headers.authorization) and response (res.headers.authorization) are redacted. - Request Cookies (
cookie): Cookie names are preserved, values are masked with<redacted>. - Response Set-Cookie (
set-cookie): Redacts only the first pair's cookie value (<name>=<redacted>) while leaving security attributes (Path,Domain,Max-Age,HttpOnly,Secure,SameSite) intact for auditing visibility. - Key matching: names are compared lowercased with
-and_removed, soauthToken,AUTH_TOKENandauth-tokenare the same key. The list insrc/redaction.tscomes from an audit ofmassive-tyrionandtabletcommand-backend-models. - Prefix kept (7 characters): any name containing
apikey(departmentApiKey,x-api-key, ...), any name ending intokenexcept pagination cursors (accessToken,refresh_token,x-tc-auth-token, ...), andsignupKey,partnerKey,cadKey,vendorKey,licenseKey,licenseCode,mark43Key,authKey,accessCode,joinCode,jwt,authHeader,sessionCookie. - Completely masked (
<redacted>): any name containingpassword,passwd,passphrase,secret,credential,privateKey,signingKeyorencryptionKey, andpass,pwd,auth_pass,salt,ssn,dateOfBirth,licenseNumber,doorCode. - Booleans, numbers and
nullunder a secret name (hasAuthSecret,minPasswordLength) are left readable. - Objects with
toJSON(Mongoose documents, axios errors) are redacted as they serialize. The caller's object is never changed. - Depth Limit (
MAX_REDACT_DEPTH = 10): values nested deeper are written as they are.
Changelog
4.0.0
- Breaking: Migrated from Winston to Pino for high-performance JSON logging directly to
stdout. - Breaking: Enforced strict
(obj, msg)signature at compile time; legacy Winston inverted calls(msg, obj)fail TypeScript build. - Added: Built-in OpenTelemetry mixin extracting
trace_idandspan_idwhen active spans exist. - Added: Express HTTP middleware powered by
pino-httpwith response and request header redaction (res.headers["set-cookie"],res.headers.authorization). - Added: Configurable and automatic pretty printing via
pino-prettyin local development with fallback to NDJSON stdout. - Added: Key-based redaction of log objects, bindings, request bodies and errors, up to 10 levels deep (
MAX_REDACT_DEPTH = 10).
