| Name | Modified | Size | Downloads / Week |
|---|---|---|---|
| Parent folder | |||
| README.md | 2026-07-14 | 9.4 kB | |
| v5.0.0 source code.tar.gz | 2026-07-14 | 841.0 kB | |
| v5.0.0 source code.zip | 2026-07-14 | 974.4 kB | |
| Totals: 3 Items | 1.8 MB | 0 | |
[5.0.0] - 2026-07-14
A ground-up rewrite. tslog is now ESM-only, zero-dependency, Node >=20, and built with TypeScript 7 / ES2022. Settings are grouped, JSON output is fields-first, and the logger gains a middleware pipeline, async transports, JSONPath masking, OpenTelemetry/pino/GenAI presets, ready-made file/http/ringbuffer/worker transports, and tree-shakeable subpath modules. v5 also adds first-class support for agents and LLMs — fields-first calls, agent/session correlation, and OTel-GenAI attributes; OpenClaw uses tslog for its agent logging. This is a breaking release — see MIGRATION_v4_to_v5.md for the upgrade path.
Added
- Grouped settings — related options now live under
pretty,json,mask,stack, andmetagroups instead of a flat list ofprettyLog*/maskValues*keys. Sub-loggers merge groups rather than overwrite them. - Fields-first JSON output — every level method is overloaded pino-style:
info(fields, message?, ...args)as well asinfo(message, ...args). A single object spreads its fields to the top level, a leading object plus string spreads fields and setsmessage, and positional args land undermessage/"1"/… Runtime metadata moves under_logMetacarrying av: 5schema marker. All JSON keys are configurable via thejsongroup. - Middleware pipeline —
logger.use(middleware)runs functions over each log context to mutatelogObj/metaor drop the log entirely (returnnull/false). - Async transports with
attachTransport()returning a detach function,logger.flush(), andSymbol.asyncDispose/Symbol.disposesupport (await using). Each transport may declare its ownminLevelandformat("pretty","json", or a custom formatter). - Advanced masking —
mask.paths(JSONPath-ish patterns such asuser.passwordor*.token),mask.regex, and amask.censorof"remove","hash", a string, or a function (withmask.hashLabel). - Presets —
tslog/presets/pino(pinoFormat,pinoTransport,toPinoLevel),tslog/otel(otelFormat,toOtelRecord,levelToSeverityNumber,OtelSeverityNumber,otelTraceContext,stringifyOtelRecord), andtslog/presets/genai(genai,genaiAttributes,genaiSummaryemitting OTelgen_ai.*fields). - Built-in transports —
tslog/transports/file(fileTransport, non-blocking, flush/dispose),tslog/transports/http(httpTransport, batched),tslog/transports/ringbuffer(ringBufferTransportwith.dump()/.clear()), andtslog/transports/worker(workerTransport, Node-only off-thread sink I/O). - Standard serializers —
tslog/serializersexportsstdSerializers(err,req,res,user), the individual serializers, and aserialize(map)middleware helper. - Context propagation —
runInContext(ctx, fn)uses AsyncLocalStorage to attach context fields to_logMetawhenmeta.attachContextis enabled. Auto-resolves on Node/Deno/Bun; on Cloudflare Workers inject one via thecontextStoragesetting (graceful no-op in browsers, with a one-time development warning). - Custom levels via the
customLevelssetting andlog(levelId, levelName, ...args). - New API surface —
child()(alias ofgetSubLogger()),isLevelEnabled(),getContext(),addLevel(),logger.if(condition),Logger.fromEnv(),defineConfig(), andTslogConfigError(thrown whenstrictConfigis on). - Subpath modules (all tree-shakeable) —
tslog/lite(minimal console wrappers preserving native line numbers),tslog/cli(also thetslogbin, an NDJSON pretty-printer for stdin),tslog/testing(createTestLogger,mockLogger),tslog/throttle(rate-limit middleware),tslog/pretty/box(box,tree), andtslog/console(wrapConsole,restoreConsole,isConsoleWrapped). - Env-aware colorization — when
typeis omitted, output isprettyeverywhere (server, CI, browser, React Native); only the coloring adapts to the environment: colored on an interactive TTY (CSS in the browser) and uncolored when stdout is piped/redirected/CI, so no ANSI escapes leak into files or log collectors. Structured JSON is opt-in viatype: "json",TSLOG_TYPE=json, or a JSON transport.NO_COLORstrips colors without switching the format;FORCE_COLORforces styled pretty. Applies to bothnew Logger()and the ready-madelog. - React Native support — detected via
navigator.product(_logMeta.runtime: "react-native", Hermes engine version when available), Hermes/JSC stack frames parsed with a hybrid parser, pretty output by default. - Real hostname in server JSON logs —
_logMeta.hostnameresolves fromHOSTNAME/HOST/COMPUTERNAME, then the OS hostname (Deno.hostname()/node:osviaprocess.getBuiltinModule), instead of defaulting to"unknown". - Tree-shakeable exports —
sideEffects: false(audited) with per-runtime conditional exports. tslog/slim— the smallest structured-JSON build (~9KB gzip vs ~19KB for the full browser entry, budget-checked in CI): the same pipeline minus masking, pretty output, and stack capture;masksettings andtype: "pretty"throw instead of silently degrading.- Buffered stdout sink (Node) — the Node entry writes
type: "json"lines through a batchedprocess.stdout.write(one write per event-loop turn, early flush past ~8KB) instead of per-lineconsole.log; drained bylogger.flush(),await using, and guardedbeforeExit/exithooks (a bareprocess.exit()loses nothing). Browser/universal entries keepconsole.log. - Time seam — an injectable top-level
clock: () => Date(deterministic tests, offset/monotonic stamping; inherited by sub-loggers, hostile clocks ignored) andjson.time: "iso" | "epoch" | false | fncontrolling the top-level timestamp representation (_logMeta.datestays UTC ISO). - Deterministic test output —
createTestLogger(settings, { now, normalize }):nowfreezes only that logger's clock (no fake-timer sledgehammer),normalize: trueyields snapshot-stable records/lines; plus a standalonenormalizeMeta(recordOrLine)scrubber (all intslog/testing). - Real OTLP/JSON in
tslog/otel—otlpFormat/toOtlpJson/toOtlpLogRecord/toOtlpAnyValue/stringifyOtlpRequestemit the collector wire format (camelCase proto3 fields, typed attributes,resourceLogs[].scopeLogs[].logRecords[]envelope,exception.*semconv mapping for logged errors), andotlpBatchBodypairs with the http transport's newencodeBodyoption to POST merged batches straight to/v1/logs. httpTransport({ encodeBody })— custom body encoder for endpoints whose payload is neither NDJSON nor a JSON array (used by the OTLP pairing above).- Conditional logging —
logger.if(condition)returns the logger when the condition is truthy and a no-op stand-in when falsy, so a per-call guard reads as a fluent chain (log.if(!ok).warn("failed", { id })). UseisLevelEnabled()to skip expensive payload construction. - Browser-native pretty objects —
pretty.passObjectsNativelyhands non-Errorarguments to the console by reference (on by default in real browsers), so DevTools renders collapsible, interactive trees; pair withpretty.levelMethodfor native warn/error stack groups. Setfalsefor log-time snapshots or text-matchable console output. - Source-mapped error positions — on Node, Bun, and Deno, logged
Errorstack frames resolve through discoverable source maps back to original.tsfile/line/column (automatic outside production; override withTSLOG_SOURCE_MAPS=on/off).
Changed
- ESM-only and Node >=20; the project now targets TypeScript 7 / ES2022.
- JSON output on Node no longer goes through
console.log(see the buffered stdout sink above) — code interceptingconsole.logmust spy onprocess.stdout.writeor usetype: "hidden"plus a transport. tslog/otelresource precedence — intoOtelRecord,resourceattributes now win over colliding per-record fields (resource identity semantics); in the OTLP shape they live in the envelope, separate from record attributes.- The default JSON shape is fields-first with
_logMeta.v: 5;name/parentNamesappear only when set (no"[undefined]"noise). - Masking is off by default —
mask.keysstarts empty; enable it explicitly.
Removed
- The CommonJS build and
require("tslog")— the package is ESM-only. - The
overwrite.*hooks (mask,toLogObj,addMeta,formatMeta,formatLogObj,transportFormatted,transportJSON,addPlaceholders) — use middleware and per-transportformatinstead. - Flat settings keys —
prettyLogTemplate/prettyError*/prettyLog*,stylePrettyLogs,maskValuesOfKeys/maskValuesRegEx/maskPlaceholder,metaProperty, andstackDepthLevel(now thecallerFrameconstructor parameter). hideLogPositionForProduction— superseded by thestackgroup and env-aware defaults.- The
loggerEnvironment/createLoggerEnvironmentsingleton — each entry point exports its own environment factory (createNodeEnvironment,createBrowserEnvironment,createUniversalEnvironment/selectEnvironment). - The nested
{"0": message}JSON shape.