@starkow/logger
why?
- i wanted to make it by my own
- it's gorgeous i think
- fixed colors for static names (logger name
'foo'will produce deterministic yet still random color every time, always readable on both dark and light terminals)! - it have log level
- file logs exist Yes
- color disable when not terminal
- child loggers (
app:db), timers, namespace filtering (LOG=app:*) - fields on every line (
log.with({ reqId })) and a json mode for production - yeah
v3 is esm-only and targets node 22+. if you're still on commonjs, use a dynamic
import()
usage
import { Logger, Color, TextStyle } from '@starkow/logger'
const log = Logger.create('foo') // log will be given random yet deterministic color
log('bar', Logger.color('baz', Color.Red, TextStyle.Bold), ':)')
alternative imports:
import { Logger } from '@starkow/logger'
import { Color, TextStyle } from '@starkow/logger/colors'
log levels
levels are ordered by severity (low → high):
LogLevel.Debug-log.debug(...)LogLevel.Info-log.info(...)LogLevel.Warn-log.warn(...)LogLevel.Error-log.error(...)LogLevel.Silent- mutes the logger completely
Logger.config.setLogLevel(level) sets the minimum severity that gets printed. so setLogLevel(LogLevel.Warn) shows warnings and errors but hides info & debug; setLogLevel(LogLevel.Error) shows only errors; setLogLevel(LogLevel.Silent) hides everything, raw logs included
the plain log(...) / log.log(...) call is raw output — it ignores the severity threshold and only goes quiet under LogLevel.Silent
levels can also be given by name: 'debug' | 'info' | 'warn' | 'error' | 'silent'
default level is LogLevel.Debug, so everything is visible out of the box. the LOG_LEVEL env var changes the default (unknown values are ignored)
LOG_LEVEL=warn node app.mjs
import { Logger, LogLevel } from '@starkow/logger'
Logger.config.setLogLevel(LogLevel.Warn) // only warn & error (and raw log) will show
const log = Logger.create('@starkow/logger')
log('is cool!') // shown (raw, not level-filtered)
log.warn('careful!') // shown
log.info('fyi') // hidden
log.debug('noise') // hidden
skipping expensive logs
a single zero-argument arrow function is only called when the line will actually be written, so costly debug output costs nothing while debug is hidden
log.debug(() => JSON.stringify(hugeState, null, 2))
for anything more involved, ask first: log.enabled(level) tells whether a call at that level would be written anywhere (console or file). without a level it answers for raw log()
if (log.enabled('debug')) {
log.debug('cache stats', collectCacheStats())
}
colors
colors are emitted automatically when it makes sense — i.e. when you're writing to an actual terminal. the check is per stream: warn/error go to stderr, so node app.mjs 2> errors.log keeps a clean file while stdout stays colorful. when output is piped or redirected, or NO_COLOR is set, they're stripped so you don't get \x1b[...m garbage in your files/pipes. FORCE_COLOR forces them back on
you can override the detection:
import { Logger } from '@starkow/logger'
Logger.config.setColor('always') // 'auto' (default) | 'always' | 'never'
file logs
import { resolve } from 'node:path'
import { Logger } from '@starkow/logger'
Logger.config.setFilePath(resolve(import.meta.dirname, 'epic.log'))
Logger.create('this will be logged')('into a file!', { 42: true })
file {dir}/epic.log will look like this:
2023-10-05T22:47:16.630Z [this will be logged] into a file! { '42': true }
writes go through a single open stream (no interleaving), failures won't crash your process, and any ansi colors are stripped before hitting the file. values are formatted just like console.log does (Maps, Sets, bigints, circular refs, %s specifiers), on a single line. errors keep their stack. call await Logger.flush() before process.exit() to make sure pending writes land
the file follows the console level unless you give it its own, e.g. a quiet console with a detailed file:
Logger.configure({ level: 'warn', fileLevel: 'debug', filePath: './app.log' })
rotating the file is best left to the system (logrotate on linux). after it moves the file, tell the logger to reopen it:
process.on('SIGHUP', () => Logger.reopenFile())
/var/log/myapp/app.log {
daily
rotate 7
compress
postrotate
kill -HUP $(cat /var/run/myapp.pid)
endscript
}
child loggers
log.child(name) creates a sub-logger namespaced under its parent. it gets its own deterministic color and nests as deep as you want
const app = Logger.create('app')
app('starting')
const db = app.child('db')
db('connected') // app:db connected
const pool = db.child('pool')
pool('acquired') // app:db:pool acquired
fields on every line
log.with(fields) returns a logger that adds those fields to every line. perfect for following one request through interleaved logs. calls chain, and children keep their parent's fields
const log = Logger.create('api')
app.use((req, res, next) => {
req.log = log.with({ reqId: randomUUID().slice(0, 8), path: req.path })
next()
})
req.log.info('user loaded', user.id)
req.log.warn('slow query', { ms: 840 })
req.log.with({ userId: 42 }).child('img')('avatar resized')
api user loaded 42 reqId=3f9a1c2e path=/users/42
api slow query { ms: 840 } reqId=3f9a1c2e path=/users/42
api:img avatar resized reqId=3f9a1c2e path=/users/42 userId=42
fields are dimmed in the console, appended to file lines, and handed to taps as entry.context
json output
for production, where logs are read by machines. one json object per line, on the console and in the file. colors, timestamps and symbols don't apply. set it in code or with LOG_FORMAT=json
Logger.configure({ format: process.env.NODE_ENV === 'production' ? 'json' : 'pretty' })
const db = Logger.create('db').with({ pool: 'main' })
db.info('connected to', 'pg-1')
db.error('query failed', new Error('timeout'))
{"time":"2026-11-28T09:14:03.120Z","level":"info","name":"db","msg":"connected to pg-1","pool":"main"}
{"time":"2026-11-28T09:14:03.410Z","level":"error","name":"db","msg":"query failed","pool":"main","err":{"name":"Error","message":"timeout","stack":"Error: timeout\n at ..."}}
levelisdebug/info/warn/error, orlogfor rawlog()- the first
Errorargument becomeserr(withcauseand extra props likecode); the rest of the arguments make upmsg - fields from
with()sit at the top level; they can't overwritetime,level,name,msgorerr - bigints become strings,
Maps objects,Sets arrays, cycles"[Circular]"
node app.mjs | jq 'select(.level == "error")'
per-logger options
instead of variadic colors you can pass an options object to Logger.create (and child) with colors and/or a per-logger level that overrides the global one
import { Logger, Color, LogLevel } from '@starkow/logger'
Logger.config.setLogLevel(LogLevel.Error) // global: only errors
const db = Logger.create('db', { colors: [Color.Cyan], level: LogLevel.Debug })
db.debug('still shown — this logger overrides the global level')
children inherit their parent's level override
timers
log.time(label) returns a function that, when called, logs the elapsed time
const done = log.time('build')
// ... work ...
done() // build: 1.23s
done('extra data') // build: 1.23s extra data
timestamps & symbols
both off by default. opt in for a richer console line
Logger.config.setTimestamps(true) // dim HH:MM:SS
Logger.config.setTimestamps(d => d.toISOString()) // or a custom formatter
Logger.config.setSymbols(true) // ✖ ⚠ ℹ ⬦ per level
with both on: 12:34:56 ✖ app:db connection failed (raw log() gets no symbol)
configuring in one go
Logger.configure takes any subset of the options; omitted keys are left as they are. Logger.config.reset() restores every default
Logger.configure({
level: 'info',
fileLevel: 'debug', // null makes the file follow `level`
format: 'pretty', // or 'json'
color: 'auto',
timestamps: true,
symbols: true,
namespaces: 'app:*',
filePath: './app.log' // null disables file logging
})
namespace filtering
a per-logger master switch, separate from log levels. drive it with the LOG env var or set it programmatically. when unset, everything is enabled
LOG=app:* node app.mjs # only app and its descendants
LOG=db,api node app.mjs # only these
LOG='*,-app:noisy' node app.mjs # everything except app:noisy
Logger.config.setNamespaces('app:*,-app:noisy')
a disabled logger is fully silent — even its raw log() call
taps
Logger.config.onLog(fn) calls fn for every emitted log — handy for shipping logs elsewhere. it returns an unsubscribe function
const off = Logger.config.onLog(entry => {
// entry: { name, level, data, context, message, timestamp }
sendSomewhere(entry)
})
off() // stop listening
reference
Logger.create(name: string, ...colors: AnyColor[]), Logger.create(name: string, options: CreateOptions)
initializes logger function
returns: LoggerInstance
Logger.create('bot', Color.Green, TextStyle.Underline)('started!')
Logger.create('db', { colors: [Color.Cyan], level: LogLevel.Debug })('connected')
Logger.configure(options: ConfigOptions)
applies several config options at once
Logger.configure({ level: LogLevel.Warn, symbols: true })
Logger.prefix(name: string, ...colors: AnyColor[])
generates current logger prefix
returns: string
const prefix = Logger.prefix('server', Color.Cyan)
console.log(prefix, 'started!')
Logger.color(text: string, ...colors: AnyColor[])
colorizes given
textwith givencolors
returns: string
const coloredFoo = Logger.color('foo', Color.Magenta, BackgroundColor.White)
console.log(coloredFoo)
Logger.colorByRGB(text: string, color: RGBColor, options?: ColorByRGBOptions)
colorizes given
textwith a 24-bit RGBcolor(foreground by default)
returns: string
Logger.colorByRGB('foo', { r: 235, g: 87, b: 87 })
Logger.colorByRGB('bar', { r: 20, g: 20, b: 20 }, { background: true })
Logger.updateLog(text: string, params?: LogUpdateParams)
updates last log line
returns: void
console.log( 'Loading: 9%' )
Logger.updateLog('Loading: 45%' )
Logger.updateLog('Loading: 77%' )
Logger.updateLog('Loading: 100% [Done!]')
Logger.flush()
awaits all pending file writes (e.g. before
process.exit)
returns: Promise<void>
await Logger.flush()
Logger.reopenFile()
closes the log file so the next write opens it again (after log rotation)
returns: void
process.on('SIGHUP', () => Logger.reopenFile())
Logger.config
runtime configuration
Logger.config.setLogLevel(LogLevel.Error) // minimum severity to print (or 'error')
Logger.config.setFileLevel('debug') // separate minimum for the file; null follows setLogLevel
Logger.config.setFormat('json') // 'pretty' | 'json' (overrides $LOG_FORMAT)
Logger.config.setColor('never') // 'auto' | 'always' | 'never'
Logger.config.setTimestamps(true) // bool | (date) => string
Logger.config.setSymbols(true) // level glyphs on/off
Logger.config.setNamespaces('app:*') // namespace filter (overrides $LOG)
Logger.config.setFilePath('./app.log') // enable file logging
Logger.config.resetFilePath() // disable file logging
Logger.config.resetSymbols() // every setter has a matching reset*()
Logger.config.reset() // restore all defaults
const off = Logger.config.onLog(entry => { ... }) // tap; returns unsubscribe
LoggerInstance
const log = Logger.create('logger')
(...data: any[]): void, log(...data: any[]): void
log( 'foo', ['bar', 13.37])
log.log('foo', ['bar', 13.37])
update(...): void
log('1')
log.update('2')
log.update('3')
log.update({ progress: 50 }) // objects are logged as data
log.update({ clearLastLine: false }, 'below') // only { clearLastLine } is read as params
long lines that wrapped across several terminal rows are fully replaced
error(...): void
log.error('failed!')
warn(...): void
log.warn('something is about to crash!')
debug(...): void
log.debug({ 42: 'the truth' })
info(...): void
log.info('this log is very mandatory keep listening to me i swear')
child(name: string, ...colors: AnyColor[]): LoggerInstance, child(name, options): LoggerInstance
const db = log.child('db') // namespaced under the parent
const pool = db.child('pool', Color.Cyan)
time(label: string): (...data: any[]) => void
const done = log.time('build')
// ... work ...
done() // build: 1.23s
with(fields: Record<string, unknown>): LoggerInstance
const req = log.with({ reqId: 'abc' }) // same name, colors and level, plus fields
req.with({ userId: 42 }) // fields merge; later ones win
enabled(level?: LogLevel | LevelName): boolean
log.enabled('debug') // would log.debug(...) be written anywhere?
log.enabled() // would a raw log(...) be written?