nc.logger
A console logger that works with zero setup: levels, colors, a small markup for styling, groups, timers and tables. In production, switch to one JSON object per line with LOG_FORMAT=json, and write to rotating files if you need to.
Markup: <% red bold Error:%> disk is full. Any style name works, plus #ff8800, bg#1e1e2e, rgb(255, 128, 0) and bgRgb(...).
Levels, from chatty to severe: trace, debug, info, warn, error, fatal. The default is info, or debug when DEBUG is set; LOG_LEVEL overrides it. Warnings and errors go to stderr.
const { logger } = require("@ix-xs/node-comfort");
import { log } from "@ix-xs/node-comfort/logger";These functions are also available at the top level: nc.log() is nc.logger.log().
nc.info("Server listening on port 3000");
nc.warn("Cache is almost full");
nc.error(new Error("Payment failed", { cause: err }));
nc.log("<% cyan bold Tip:%> press <% bgWhite black q %> to quit");nc.logger.Functions
nc.logger.log()
log(...args: unknown[]): typeof nc.loggerPrints a message without a badge. Strings support markup, objects are pretty-printed, and several arguments are joined with spaces.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
Example
nc.log("<% green ✔ Saved %> in <% bold 12ms %>");
nc.log("user:", { id: 1, roles: ["admin"] });nc.logger.trace()
trace(...args: unknown[]): typeof nc.loggerVery detailed diagnostics, shown only at the trace level.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
nc.logger.debug()
debug(...args: unknown[]): typeof nc.loggerDiagnostics for developers, shown at the debug level (the default when DEBUG is set).
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
Example
nc.debug("cache miss", { key });nc.logger.info()
info(...args: unknown[]): typeof nc.loggerAn informational message.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
Example
nc.info("Server listening on http://localhost:3000");nc.logger.success()
success(...args: unknown[]): typeof nc.loggerA success message.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
Example
nc.success("Database connected");nc.logger.warn()
warn(...args: unknown[]): typeof nc.loggerA warning, written to stderr.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
nc.logger.error()
error(...args: unknown[]): typeof nc.loggerAn error, written to stderr. Error objects show their stack trace and their chain of causes.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
Example
nc.error(new Error("Cannot save order", { cause: dbError }));nc.logger.fatal()
fatal(...args: unknown[]): typeof nc.loggerA fatal error, written to stderr. It doesn't stop the process; call process.exit(1) yourself if you mean to.
Parameters
| Name | Type |
|---|---|
...args | ...unknown |
Returns typeof import("./Logger")
nc.logger.group()
group(label?: string): typeof nc.loggerPrints a label and indents what follows, until groupEnd(). Groups nest.
Parameters
| Name | Type |
|---|---|
labeloptional | string |
Returns typeof import("./Logger")
Example
nc.group("Startup").info("Loading config");
nc.group("Database").success("Connected").groupEnd();
nc.groupEnd();nc.logger.groupEnd()
groupEnd(): typeof nc.loggerCloses the current group.
Returns typeof import("./Logger")
nc.logger.timeStart()
timeStart(label?: string): typeof nc.loggerStarts a named timer. timeEnd() prints the elapsed time.
Parameters
| Name | Type | Description |
|---|---|---|
labeloptional | string | Default: "default" |
Returns typeof import("./Logger")
Example
nc.timeStart("import");
await importProducts();
nc.timeEnd("import"); // "import: 1.24s"nc.logger.timeEnd()
timeEnd(label?: string): typeof nc.loggerPrints the time since timeStart() with the same label.
Parameters
| Name | Type | Description |
|---|---|---|
labeloptional | string | Default: "default" |
Returns typeof import("./Logger")
nc.logger.table()
table(rows: Record<string, unknown>[] | unknown[][], options?: TableOptions): typeof nc.loggerPrints rows as a table.
Parameters
| Name | Type |
|---|---|
rows | Array<Record<string, unknown>> | unknown[][] |
optionsoptional | TableOptions |
Returns typeof import("./Logger")
Example
nc.table([{ name: "Ada", role: "admin" }, { name: "Bob", role: "user" }]);nc.logger.box()
box(text: string, options?: BoxOptions): typeof nc.loggerPrints text in a box. Nice for startup banners.
Parameters
| Name | Type |
|---|---|
text | string |
optionsoptional | BoxOptions |
Returns typeof import("./Logger")
Example
nc.box("Server ready\nhttp://localhost:3000", { title: "my-app", borderColor: "green" });nc.logger.divider()
divider(title?: string): typeof nc.loggerPrints a horizontal line, with an optional title in it.
Parameters
| Name | Type |
|---|---|
titleoptional | string |
Returns typeof import("./Logger")
nc.logger.setLevel()
setLevel(level: LogLevel): typeof nc.loggerSets the minimum level.
Parameters
| Name | Type |
|---|---|
level | LogLevel |
Returns typeof import("./Logger")
Throws RangeError For an unknown level.
Example
nc.setLevel("warn"); // warnings and errors only
nc.setLevel("silent"); // nothingnc.logger.getLevel()
getLevel(): LogLevelThe current minimum level.
Returns LogLevel
nc.logger.isLevelEnabled()
isLevelEnabled(level: LogLevel): booleanWould this level be printed? Use it to skip building expensive debug output.
Parameters
| Name | Type |
|---|---|
level | LogLevel |
Returns boolean
Example
if (nc.isLevelEnabled("debug")) nc.debug(buildHugeReport());nc.logger.configure()
configure(options: LoggerOptions): typeof nc.loggerChanges several settings at once.
Parameters
| Name | Type |
|---|---|
options | LoggerOptions |
Returns typeof import("./Logger")
Example
nc.configure({ level: "debug", file: "logs/app.log" });
nc.configure({ format: "json", fields: { service: "api" } });nc.logger.setTimestamp()
setTimestamp(value: string | boolean): typeof nc.loggerShows or hides timestamps, or sets their pattern.
Parameters
| Name | Type |
|---|---|
value | boolean | string |
Returns typeof import("./Logger")
Example
nc.setTimestamp(false);
nc.setTimestamp("YYYY-MM-DD HH:mm:ss.SSS");nc.logger.setDelimiter()
setDelimiter(options?: { open?: string; close?: string; } | undefined): typeof nc.loggerChanges the markup delimiters, for when <% clashes with a template engine.
Parameters
| Name | Type |
|---|---|
optionsoptional | { open?: string, close?: string } |
Returns typeof import("./Logger")
Example
nc.setDelimiter({ open: "{{", close: "}}" });
nc.log("{{red Hello}} world");nc.logger.createLogger()
createLogger(options?: LoggerOptions): LoggerCreates a logger with its own settings.
Parameters
| Name | Type |
|---|---|
optionsoptional | LoggerOptions |
Returns Logger
Example
const log = nc.createLogger({ scope: "api", timestamp: "HH:mm:ss.SSS" });
log.info("GET /users 200"); // [14:30:05.120] [api] ℹ INFO GET /users 200
log.child("db").debug("query took 12ms");
const prod = nc.createLogger({ format: "json", fields: { service: "billing" } });
prod.error("charge failed", { orderId: 42 }, error);Types
Import any of them in TypeScript with import type { LogFileOptions } from "@ix-xs/node-comfort", or in JavaScript with import("@ix-xs/node-comfort").LogFileOptions.
LogFileOptions
Writing logs to a file.
| Property | Type | Description |
|---|---|---|
path | string | The file to append to. Folders are created, colors removed. |
maxSizeoptional | string | number | Rotate past this size, like "10MB". |
maxFilesoptional | number | How many rotated files to keep. Defaults to 5. |
Logger
A logger from createLogger(). Every method returns the logger, so calls chain.
| Property | Type | Description |
|---|---|---|
log | (...args: unknown[]) => Logger | A plain message, no badge. Supports markup. |
trace | (...args: unknown[]) => Logger | Very detailed diagnostics, hidden unless the level is trace. |
debug | (...args: unknown[]) => Logger | Diagnostics, hidden unless the level is debug or lower. |
info | (...args: unknown[]) => Logger | An ℹ INFO message. |
success | (...args: unknown[]) => Logger | A ✔ OK message. |
warn | (...args: unknown[]) => Logger | A ⚠ WARN message, on stderr. |
error | (...args: unknown[]) => Logger | An ✖ ERROR message, on stderr. Errors show their stack and cause. |
fatal | (...args: unknown[]) => Logger | An ✖ FATAL message, on stderr. |
group | (label?: string) => Logger | Prints a label and indents what follows. Groups nest. |
groupEnd | () => Logger | Closes the current group. |
timeStart | (label?: string) => Logger | Starts a named timer. |
timeEnd | (label?: string) => Logger | Prints how long since timeStart(label). |
table | (rows: Record<string, unknown>[] | unknown[][], options?: TableOptions) => Logger | Prints rows as a table. |
box | (text: string, options?: BoxOptions) => Logger | Prints text in a box. |
divider | (title?: string) => Logger | Prints a horizontal line. |
child | (scope: string, options?: LoggerOptions) => Logger | A logger with the same settings and a nested scope. Its fields are added to the parent's. |
setLevel | (level: LogLevel) => Logger | Changes the minimum level. |
getLevel | () => LogLevel | The current minimum level. |
isLevelEnabled | (level: LogLevel) => boolean | Would this level be printed? Skip expensive debug output when it wouldn't. |
configure | (options: LoggerOptions) => Logger | Changes several settings at once. |
LoggerOptions
Options for createLogger() and configure().
| Property | Type | Description |
|---|---|---|
leveloptional | LogLevel | Hide messages below this level. Defaults to LOG_LEVEL, else "info". |
scopeoptional | string | Shown before each message, like [db]. Child loggers extend it (db:pool). |
timestampoptional | string | boolean | true shows [HH:mm:ss], false hides it, a string is a time.format pattern. Defaults to true. |
formatoptional | "pretty" | "json" | "json" writes one object per line, for log collectors. Defaults to LOG_FORMAT, else "pretty". |
delimiteroptional | { open?: string; close?: string; } | Markup delimiters. Defaults to <% and %>. |
colorsoptional | boolean | Force colors on or off. By default, it depends on the terminal. |
stdoutoptional | LogStream | Where trace to info go. Defaults to process.stdout. |
stderroptional | LogStream | Where warn, error and fatal go. Defaults to process.stderr. |
fileoptional | string | LogFileOptions | Also write every message to a file. |
fieldsoptional | Record<string, unknown> | Added to every JSON record, like a service name. |
LogLevel
Log levels, from the most verbose to the most severe. silent hides everything.
type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal" | "silent"LogStream
Where logs go: process.stdout, a file stream, or anything with a write(text) method.
| Property | Type | Description |
|---|---|---|
write | (text: string) => unknown |