@en32/debuggy
v3.2.0
Published
Wrap any expression, log contextual debug info, and pass the original value through. Zero dependencies, Node.js and Bun, shipped as TypeScript source.
Maintainers
Readme
@en32/debuggy
Wrap any expression, print contextual debug output, and pass the original value through, so it can be dropped into existing code without changing it.
| | |
| :---: | :---: |
|
|
|
|
|
|
| | |
import { debuggy } from "@en32/debuggy";
const users = await debuggy(`[SQL] Userdata %t`)(User.findAll());[SQL] Userdata
├─ at : src/services/user.ts:42:19
├─ in : UserService.list
├─ status : resolved (Promise)
├─ time : 12.48 ms
└─ result :
┌─────────┬────┬───────┐
│ (index) │ id │ name │
├─────────┼────┼───────┤
│ 0 │ 1 │ Alice │
│ 1 │ 2 │ Bob │
└─────────┴────┴───────┘- Zero dependencies. Node.js ≥ 20 and Bun ≥ 1.4.
- Shipped as TypeScript source (
exportspoint to.ts, no build step). Use it from Bun,tsx,ts-node, or a bundler. Node's--experimental-strip-typesalso works (imports use explicit.tsextensions). - Disabled in production: every function is a no-op that returns its input.
Mode rules
debuggy is active only in development mode:
NODE_ENV=productionalways wins (DEBUGGYis ignored).- Otherwise a non-empty
DEBUGGYenables it. - Otherwise
NODE_ENV=developmentenables it. - Anything else is production.
bun run server # production: everything is a no-op
DEBUGGY=SQL,POST bun run server # development, only SQL and POST tags
NODE_ENV=development bun run server # development, all tags
NODE_ENV=production DEBUGGY=SQL bun run server # production (production wins)The mode is evaluated once at module load. Calling debuggy.enable() alone
does not switch the mode on. In production the argument expression itself
(User.findAll()) is still evaluated, as JavaScript requires.
Labels and placeholders
[TAG1][TAG2] title with %placeholders and <hy>styles<0>Leading [TAG] blocks are used for filtering. Result placeholders choose how
the result is rendered; meta placeholders replace the whole layout. Style
markup colors the title (see Styles).
| Result | Renders the result as |
| ------ | ---------------------------------------- |
| %t | table (falls back to %o) |
| %j | pretty JSON, safe for BigInt/circular |
| %J | one-line JSON |
| %o | util.inspect with depth (default) |
| %O | util.inspect with unlimited depth |
| %s | string |
| %% | literal % |
| Meta | Content | Meta | Content |
| ---- | ----------------------------------------- | ---- | ------------------------------------ |
| %x | expression text | %e | duration (12.48ms) |
| %v | destination variable | %S | status |
| %p | file:line:col | %T | ISO timestamp (UTC) |
| %f | file name | %g | tags (SQL,SLOW) |
| %l | line:col | %m | heap delta (+1.2MB) |
| %n | enclosing function (or scope name) | %c | element count |
| %D | local date and time (2026-11-29 15:03:12) | %k | result type (Array(3)) |
debuggy(`[SQL] %f:%l %n took %e %k %J`)(q);
// [SQL] user.ts:42:19 UserService.list took 12.48ms Array(3) [{"id":1,...}]Multi-line results in a custom layout are placed on their own lines.
%T is the ISO timestamp in UTC (2026-11-29T07:03:12.481Z); %D is the same
moment in local time as YYYY-MM-DD hh:mm:ss (24 hours, no milliseconds, not
affected by the system locale). Both are taken when the entry is logged, that is
when the value settles, not when debuggy(label) is called.
debuggy("[JOB] %D start %n")();
// [JOB] 2026-11-29 15:03:12 start nightlySync%q is a marker: it prints nothing and keeps the entry out of the log file
(see Log file). The terminal and logger still receive it. It can
stand anywhere in the title, never counts as a placeholder (so the layout and the
template do not change) and can be escaped as %%q.
debuggy("[SQL] users %q")(rows); // terminal only, not written to the log fileScopes
The enclosing function (%n) is read from the stack. Anonymous functions, such
as inline route handlers (app.get("/users", async (c) => { ... })), are
reported as <anonymous>, because the surrounding frames describe a different
function. To get a reliable name, wrap the handler in a scope:
app.get("/users", (c) =>
debuggy.scope("GET /users", async () => {
const rows = await debuggy("[SQL] %n %t")(db.users.findAll());
// [SQL] GET /users ...
}),
);The scope name is stored in an AsyncLocalStorage, so it follows awaits. It is
used by %n, shown as a scope row in the default layouts, and exposed as
ctx.scope and entry.scope. Inner scopes win. In production scope() only calls fn.
Styles
A label title can be colored with <codes> markup. Every letter between < and
> is one style code, so <hy> is bold + yellow.
| Code | Style | Code | Foreground | Code | Background |
| ---- | ---------- | ---- | ---------- | ---- | ---------- |
| 0 | reset | k | black | K | black |
| h | bold | r | red | R | red |
| d | dim | g | green | G | green |
| u | underline | y | yellow | Y | yellow |
| | | b | blue | B | blue |
| | | m | magenta | M | magenta |
| | | c | cyan | C | cyan |
| | | w | white | W | white |
debuggy(`[SQL] <hy>Slow query<0> took %e`)(q); // bold yellow title, plain duration
debuggy(`[API] <R>FAILED<0> %S`)(req); // red background badgeRules:
- Styles apply to the title only;
[TAG]colors are automatic. Tags must come first, so<r>[SQL] xis not tagged. - A style stays active until
<0>or the end of the label. An automatic reset is added, so a style never leaks into the rest of the output. - Markup works with every placeholder:
<r>%e<0>colors the duration. - Style markup is not a placeholder: a label with only styles still uses the
default template (
template.set) and the built-in layout. <<is a literal<(like%%). Text that is not a valid style tag, such asArray<string>, is printed as-is. To print a literal<hy>, write<<hy>.- Colors follow the usual rules (TTY,
NO_COLOR,FORCE_COLOR). When colors are off the markup is removed and no escape codes are written. format: "json"never contains escape codes:titleis plain text andlabelkeeps the original string, markup included.- Only the label (and
ctx.style()in templates) is parsed; results, errors and other values are never interpreted as markup.
Templates
debuggy.template.add("short", (ctx) => ctx.write(`${ctx.at} → ${ctx.fmt.json(ctx.result, false)}`));
debuggy(`[SQL] Users`, "short")(q); // registered template
debuggy(`[SQL] Users`, (ctx) => ctx.write(ctx.expr ?? "?"))(q); // inline template
debuggy.template.set("short"); // default templatePrecedence: (1) template argument, (2) placeholders in the label,
(3) template option (per call > create() > configure()),
(4) global default template (template.set), (5) built-in layout. When a
template argument is used, placeholders and style markup are removed from
ctx.title.
The template registry and template.set are global per process. To give one
instance its own default template without touching the others, use the
template option (a registered name or an inline function):
export const dbg = debuggy.create(); // built-in layout
export const idbg = debuggy.create({ template: Label }); // its own templateTemplates can use styles through ctx.styledTitle (the label title with its
markup applied) and ctx.style() (any markup string). ctx.write() does not
parse markup, so data is never interpreted by accident:
debuggy.template.add("alert", (ctx) =>
ctx.write(
ctx.style(`<hr>ALERT<0> ${ctx.fmt.escapeStyle(String(ctx.result))}`),
ctx.styledTitle,
),
);Always pass dynamic text through ctx.fmt.escapeStyle() when it is placed
inside markup.
Label-only logs
Call the returned function without a value to log only the label, call site and scope:
debuggy("[APP] Hello world")();[APP] Hello world
├─ at : src/main.ts:12:3
└─ in : <anonymous>debuggy(label)(undefined) passes a value (undefined) and is logged as usual.
For a label-only entry:
prettyandcompactomitstatus,timeandresult;jsonandloggerentries omitresult,resultTypeandresultCount.- Result placeholders (
%t %j %J %o %O %s) render as empty text;%cand%krender as-. - Templates receive
ctx.hasResult === falseandctx.result === undefined. Checkctx.hasResultbefore printing the value in your own templates. - The ready-made templates skip the value (and the duration) automatically.
Combined with create({ template: Label }) this gives a dedicated helper for
plain log lines:
import { Label } from "@en32/debuggy/templates";
export const idbg = debuggy.create<DebugTag, true>({ template: Label });
idbg("[APP] Hello world")(); // [APP] Hello world src/main.ts:12:3Tags per instance or call
The tags option adds tags to every label of an instance, so the labels do not
need [TAG] blocks:
const sql = debuggy.create({ tags: "SQL" });
const http = debuggy.create({ tags: "HTTP|GET" }); // or "HTTP, GET" or ["HTTP", "GET"]
sql("users")(query()); // same as debuggy("[SQL] users")(query())
http("show")(handler()); // same as debuggy("[HTTP][GET] show")(handler())
debuggy("save", { tags: "AUDIT" })(write()); // one call- Several tags are separated by a comma,
|or a space; arrays work too. A tag may only containA-Z a-z 0-9 _ . : -; anything else is ignored with one warning. - The effective tags are the tags of the instance, then of the call, then of the
label, without duplicates. They are used by the filter, the output prefix,
entry.tags/ctx.tagsand the{tag}log file placeholder. - Chained
create()calls accumulate their tags:debuggy.create({ tags: "DB" }).create({ tags: "SLOW" })logs[DB][SLOW]. tagsis not available inconfigure()(a tag on every entry would be useless).- With
requireTag(see Compile-time tag validation),create({ tags })returns a function whose labels need no tag.
Tag filter
debuggy.enable("SQL,POST"); // replace filter
debuggy.enable.add("PUT"); // add to filter
debuggy.enable("*,-SQL"); // everything except SQL
debuggy.disable(); // nothing
debuggy.reset(); // back to the DEBUGGY env valuePatterns are separated by a comma, | or whitespace ("SQL|POST"), are
case-insensitive, and support * wildcards (HTTP:*) and - exclusions
(which always win). Untagged labels are printed only when the filter contains *
(the default when DEBUGGY is unset).
Compile-time tag validation (optional)
// per instance
export const debuggy = base.create<"SQL" | "POST">();
// require a tag on every label
export const strict = base.create<"SQL" | "POST", true>();// or globally, via module augmentation
declare module "@en32/debuggy" {
interface TagRegistry { SQL: true; POST: true }
interface DebuggyConfig { requireTag: true }
}Only literal labels are validated. Runtime behavior is unchanged.
Global usage (optional)
To call debuggy in every file without importing it, import the global entry
once in your main file:
// index.ts (must run before modules that use debuggy at top level)
import "@en32/debuggy/global";// any other file, no import needed
const rows = await debuggy("[SQL] users")(db.users.findAll());The entry registers globalThis.debuggy and declares its type, so the editor and
tsc accept the bare identifier. Requirements:
- The entry file must be part of your TypeScript program (covered by
include). - Static imports are evaluated before the importing module's own body, so top-level
code of modules imported before
@en32/debuggy/globalcannot see the global yet. Put the global import first. - Tag validation through
TagRegistry/DebuggyConfigaugmentation still applies. - To use your own configured instance instead, declare it yourself:
globalThis.debuggy = base.create<"SQL" | "POST">()with a matchingdeclare global { var debuggy: typeof base }.
Promises and thenables
| Input | Behavior |
| ------------------------------ | ------------------------------------------------------------ |
| Plain value | Logged immediately, same object returned |
| Native Promise | Logged on settle, a derived Promise is returned (unhandled rejections stay visible) |
| Other thenable, skip (default) | .then is never called; logged as thenable; same object |
| Other thenable, wrap | A Proxy forwards the consumer's then/catch/finally exactly once; one entry per execution |
| Other thenable, observe | debuggy calls .then once (only safe for eager thenables) |
Lazy query builders (Knex, Mongoose Query, Prisma) run on every .then(), so
use { thenable: "wrap" } for them. A frozen target or a failing Proxy falls back
to skip silently.
Log file
Set file to mirror the text output to a file. It works in development mode
only; in production no file is created or opened.
debuggy.configure({ file: "logs/debug.log" }); // terminal + file
debuggy.configure({ file: { path: "logs/debug.log", console: false } }); // file only
const sql = debuggy.create({ file: "logs/sql-{date}.log" }); // one file per day
debuggy("[HOT] loop", { file: false })(value); // off for one call2026-11-29 15:03:12 [SQL] Userdata
├─ at : src/services/user.ts:42:19
└─ result : ...| file field | Default | Description |
| ------------ | ------- | ------------------------------------------------------------------- |
| path | — | Relative to process.cwd() or absolute. {date} becomes YYYY-MM-DD (local time), {tag} the tag name, see One file per tag |
| append | true | false truncates the file once per process |
| console | true | Also write to stderr; false writes to the file only |
| stamp | true | Prefix the first line of each entry with YYYY-MM-DD hh:mm:ss |
A string is shorthand for { path }. file: false disables a file inherited from
create(), configure() or DEBUGGY_FILE.
- The file receives the same text as the terminal, without colors. Layouts,
templates (
ctx.write()) andformat: "compact"all work the same way. jsonlines are written as is: they already carrytimestamp, so no prefix is added and the file stays valid NDJSON.- A
%Din the label together withstamp: trueprints the time twice; setstamp: falsewhen the label carries its own timestamp. - A template that calls
ctx.write()several times (for examplecompose) gets one prefix per call. - Missing directories are created. Writes are synchronous, so entries keep their order and survive a crash.
- If the file cannot be opened or written, one warning is printed and entries keep
going to stderr, even with
console: false. - With
loggerand no template there is no text output, so nothing is written to the file. Useformat: "json", or write the file from thelogger. - There is no rotation or size limit: use
{date}or an external tool such aslogrotate. Results can contain sensitive data, so keep the log directory out of version control. - Several processes can append to the same file; short entries are safe, very large ones may interleave.
- A
%qin the label keeps that entry out of the file (stderr still gets it, even withconsole: false).{ file: false }does the same for one call.
One file per tag
Put {tag} in the path and every tag gets its own file. Three ways, from the
simplest to the most automatic:
// 1. One instance per file (works without {tag}); the tag is written in the label
const sql = debuggy.create({ file: "logs/SQL.log" });
const http = debuggy.create({ file: "logs/HTTP.log" });
sql("[SQL] users")(query());
http("[HTTP] show")(handler());
// 2. Tags declared once per instance, so the labels need no tag
const sql2 = debuggy.create({ tags: "SQL", file: "logs/SQL.log" });
const http2 = debuggy.create({ tags: "HTTP|GET", file: "logs/HTTP.log" });
sql2("users")(query());
http2("show")(handler());
// 3. Automatic routing with {tag} (recommended)
debuggy.configure({ file: "logs/{tag}-{date}.log" });
const sql3 = debuggy.create({ tags: "SQL" });
sql3("users")(query()); // logs/SQL-2026-11-29.log
sql3("users %q")(query()); // terminal onlyWith {tag}:
- An entry is written to one file per tag:
[SQL][SLOW]goes toSQLandSLOWfiles. It is printed to stderr only once. - An entry without tag goes to
default(logs/default.log). - Characters that are unsafe in file names become
_:HTTP:usersis written toHTTP_users.log. A tag made only of dots (.,..) becomes_. {tag}and{date}are resolved separately for each entry, in any order and also in directory names:
| path | [SQL] on 2026-11-29 | [HTTP:users] on 2026-11-30 |
| ------------------------ | --------------------------- | --------------------------------- |
| logs/{tag}.log | logs/SQL.log | logs/HTTP_users.log |
| logs/{tag}-{date}.log | logs/SQL-2026-11-29.log | logs/HTTP_users-2026-11-30.log |
| logs/{date}/{tag}.log | logs/2026-11-29/SQL.log | logs/2026-11-30/HTTP_users.log |
logs/{tag}-{date}.log gives every tag its own file per day. Use
logs/{date}/{tag}.log to archive or delete a whole day at once.
HTTP:usersandHTTP_usersshare one file, and on case-insensitive file systems so doSQLandsql.- A path without
{tag}keeps writing one file per entry, as before. SLOWfromslowMsor theTimingtemplate is a marker, not a tag: only a[SLOW]written as a tag creates aSLOWfile.DEBUGGY_FILEaccepts{tag}and{date}as well.
Options
| Option | Default | Description |
| ----------- | ---------- | ------------------------------------------------------- |
| source | "auto" | true shows expr/var; "auto" reads lazily; false never |
| thenable | "skip" | "skip" \| "wrap" \| "observe" |
| depth | 2 | Inspect depth for %o |
| maxLength | 2000 | Max length of each rendered result or error text; 0 = unlimited |
| maxRows | 50 | Max rows for %t |
| format | "pretty" | "pretty" \| "compact" \| "json" (NDJSON) |
| timestamp | false | Add a timestamp row / entry field |
| memory | false | Capture heap delta (automatic with %m) |
| result | true | Show the result |
| stack | false | Show the stack of rejected errors |
| slowMs | — | Mark entries slower than this as (SLOW) |
| logger | — | Receives every DebuggyEntry; suppresses built-in output |
| file | — | Mirror text output to a file, see Log file |
| tags | — | Tags added to every label (create() or one call), see Tags per instance or call |
| template | — | Default template of the instance or call: registered name or inline function |
Precedence: per call > create() defaults > configure() > environment > built-in.
| Environment | Meaning |
| ------------------- | ---------------------------------------- |
| NODE_ENV | production disables everything |
| DEBUGGY | Enables development mode and sets the tag filter |
| DEBUGGY_SOURCE | 1 / 0 / auto |
| DEBUGGY_THENABLE | skip / wrap / observe |
| DEBUGGY_FORMAT | pretty / compact / json |
| DEBUGGY_DEPTH | inspect depth |
| DEBUGGY_FILE | log file path, see Log file |
| NO_COLOR | disable colors (and remove style markup) |
| FORCE_COLOR | enable colors even when stderr is not a TTY |
Notes and limitations
- Output goes to stderr, one atomic write per entry (and to the log file when
fileis set). maxLengthlimits each rendered result or error text (every placeholder separately) in the built-in layouts,jsonlines and the ready-made templates. The cut text ends with… (N more chars). Injsonlines the value becomes the truncated text and the line getsresultTruncatedorerrorTruncated: true, so it stays valid JSON. Table rows and cells (maxRows, 80 characters per cell) andloggerentries are not affected. A value is rendered in full before it is cut: the limit protects the size of the output, not CPU or memory for huge values.- Labels written before this feature that contain
<<now print a single<. - Errors in templates, renderers, or loggers are caught and reported as a single stderr line; they never affect the application.
- If
debuggy(label)is called and the value expression throws synchronously, the second call never happens, so nothing is logged. awaitinside the argument (debuggy("x")(await foo())) is reported assyncand the duration includes thatawait.- Results are rendered when the value settles, not deep-cloned; later mutations show up in the output.
- Positions are exact when running TypeScript directly (Bun,
tsx,--experimental-strip-types). For compiled output use--enable-source-maps. Minified/bundled code reports bundle positions. - The reported function name always belongs to the same frame as the reported
position. Anonymous callers are shown as
<anonymous>(see Scopes). - Expression/variable extraction is a dependency-free heuristic. The source text at
the reported position is verified; if it does not match, the same line is
searched, and if that fails a single warning is written per file and
%x/%vstay empty (bundled code without source maps, stale files, REPL/eval). - Filter and template registry are global per process (per worker thread). The
templateoption is the per-instance alternative totemplate.set. - Bun: make sure
bun run <script>does not setNODE_ENV=developmenton your setup, otherwise development mode is active withoutDEBUGGY.
Ready-made templates
@en32/debuggy/templates exports templates you can pass as the second argument:
import { debuggy } from "@en32/debuggy";
import { Table, ErrorsOnly, compose } from "@en32/debuggy/templates";
await debuggy("[SQL] users", Table)(db.users.findAll());
await debuggy("[SQL] users", compose(Table, ErrorsOnly))(db.users.findAll());| Template | Output |
| ------------ | ------------------------------------------------------------------- |
| Minimal | one line: title, status, duration |
| Timing | title, function, duration; SLOW above slowMs |
| Table | title, call site and the value as a table |
| Json | title with duration and the value as pretty JSON |
| Label | title and call site on one line, never the value (for debuggy(label)()) |
| Location | file:line:col and function (or scope) first, then the value |
| Expression | variable = expression read from the source, then the value |
| ErrorsOnly | nothing unless the value rejected; includes the stack with stack: true |
| Classic | full report: ####### header, at / File / Line / timestamp rows, value, separator, executed time |
| Hash | short report: ###### header, # file:line:col, value |
| Banner | a highlighted box with the title only (marks a position in the output) |
| Warning, Danger | highlighted title (yellow / red background): short and full layout |
| Debug, Info | full report with a DEBUG: / INFO: title prefix |
| compose(...templates) | runs several templates for the same entry |
| highlight(style, layout?), level(name) | factories for your own highlighted / prefixed variants |
The templates record maps lower-case names (minimal, table, errorsOnly, classic, ...)
to the same functions, for debuggy.template.add(name, template).
Examples
Runnable examples are in examples/ (they import from the relative
../src/index.ts; use @en32/debuggy in your own code):
| File | Shows |
| ------------------------------------------------------------ | -------------------------------------------------------- |
| 01-basic.ts | sync / Promise / rejection, tags, custom layouts, %x %v |
| 02-async-handlers.ts | function names with async code, debuggy.scope() |
| 03-thenables.ts | skip, wrap and observe for lazy query builders |
| 04-templates-and-logger.ts | tag filter, templates, create(), logger |
| 05-nested-imports.ts | call sites across nested files, sync/async, barrel and dynamic import() |
| 06-ready-made-templates.ts | Minimal, Timing, Table, Json, Location, Expression, ErrorsOnly, compose, registration by name |
| 07-report-styles.ts | Classic, Hash, Banner, Warning, Danger, Debug, Info, highlight(), level() |
| 08-global.ts | @en32/debuggy/global |
| 09-instances-and-label-only.ts | create({ template }), label-only calls, Label |
| 10-log-file.ts | file option, {date}, console: false, NDJSON file, %D |
| 11-log-per-tag.ts | tags option, {tag} log files, %q |
DEBUGGY='*' bun examples/02-async-handlers.tsSee API.md for the full reference.
Source code
- Repository: https://github.com/enix1032/debuggy
License
MIT © @en32
