# @starkow/logger

> simple yet effective logger

Latest version **4.2.0** (published 2026-11-28) · WTFPL license · 0 weekly downloads

## Install

```sh
npm install @starkow/logger
pnpm add @starkow/logger
yarn add @starkow/logger
bun add @starkow/logger
```

## Health

**Score 70/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 4.2.0 |
| Published | 2026-11-28 |
| First published | 2022-06-22 |
| Weekly downloads | 0 |
| License | WTFPL |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=22 |
| Dependencies | 0 |
| Unpacked size | 124.9 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 1 |
| Author | starkow |
| Maintainers | nitrojs |
| Keywords | logger |

## Links

- npm: https://www.npmjs.com/package/@starkow/logger
- Repository: https://github.com/nitreojs/logger
- Homepage: https://github.com/nitreojs/logger#readme
- Issues: https://github.com/nitreojs/logger/issues
- npm.io page: https://npm.io/package/@starkow/logger

## Alternatives

- [cli-color](https://npm.io/package/cli-color.md) — 3.4M weekly downloads
- [log](https://npm.io/package/log.md) — 1.3M weekly downloads
- [logstash-client](https://npm.io/package/logstash-client.md) — 4.5K weekly downloads
- [@nocobase/plugin-logger](https://npm.io/package/@nocobase/plugin-logger.md) — 2.0K weekly downloads
- [child-process-debug](https://npm.io/package/child-process-debug.md) — 695 weekly downloads

## Recent versions

- 4.2.0 (latest) — 2026-11-28
- 3.0.0 — 2026-06-02
- 2.3.1 — 2023-10-05
- 2.2.0 — 2023-10-05
- 2.1.0 — 2022-10-28
- 2.0.0 — 2022-10-28
- 1.0.1 — 2022-06-22
- 1.0.0 — 2022-06-22

## README

## @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

> [!NOTE]
> v3 is **esm-only** and targets node 22+. if you're still on commonjs, use a dynamic `import()`

### usage

```ts
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:

```ts
import { Logger } from '@starkow/logger'
import { Color, TextStyle } from '@starkow/logger/colors'
```

#### log levels

levels are ordered by severity (low → high):

1. `LogLevel.Debug` - `log.debug(...)`
2. `LogLevel.Info` - `log.info(...)`
3. `LogLevel.Warn` - `log.warn(...)`
4. `LogLevel.Error` - `log.error(...)`
5. `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)

```sh
LOG_LEVEL=warn node app.mjs
```

```ts
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

```ts
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()`

```ts
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:

```ts
import { Logger } from '@starkow/logger'

Logger.config.setColor('always') // 'auto' (default) | 'always' | 'never'
```

#### file logs

```ts
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:

```log
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 (`Map`s, `Set`s, 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:

```ts
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:

```ts
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

```ts
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

```ts
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`

```ts
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'))
```

```json
{"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 ..."}}
```

- `level` is `debug` / `info` / `warn` / `error`, or `log` for raw `log()`
- the first `Error` argument becomes `err` (with `cause` and extra props like `code`); the rest of the arguments make up `msg`
- fields from `with()` sit at the top level; they can't overwrite `time`, `level`, `name`, `msg` or `err`
- bigints become strings, `Map`s objects, `Set`s arrays, cycles `"[Circular]"`

```sh
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

```ts
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

```ts
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

```ts
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

```ts
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

```sh
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
```

```ts
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

```ts
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`

```js
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

```js
Logger.configure({ level: LogLevel.Warn, symbols: true })
```

### `Logger.prefix(name: string, ...colors: AnyColor[])`

> generates current logger prefix

returns: `string`

```js
const prefix = Logger.prefix('server', Color.Cyan)

console.log(prefix, 'started!')
```

### `Logger.color(text: string, ...colors: AnyColor[])`

> colorizes given `text` with given `colors`

returns: `string`

```js
const coloredFoo = Logger.color('foo', Color.Magenta, BackgroundColor.White)

console.log(coloredFoo)
```

### `Logger.colorByRGB(text: string, color: RGBColor, options?: ColorByRGBOptions)`

> colorizes given `text` with a 24-bit RGB `color` (foreground by default)

returns: `string`

```js
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`

```js
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>`

```js
await Logger.flush()
```

### `Logger.reopenFile()`

> closes the log file so the next write opens it again (after log rotation)

returns: `void`

```js
process.on('SIGHUP', () => Logger.reopenFile())
```

### `Logger.config`

> runtime configuration

```js
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`

```js
const log = Logger.create('logger')
```

#### `(...data: any[]): void`, `log(...data: any[]): void`

```js
log(    'foo', ['bar', 13.37])
log.log('foo', ['bar', 13.37])
```

#### `update(...): void`

```js
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`

```js
log.error('failed!')
```

#### `warn(...): void`

```js
log.warn('something is about to crash!')
```

#### `debug(...): void`

```js
log.debug({ 42: 'the truth' })
```

#### `info(...): void`

```js
log.info('this log is very mandatory keep listening to me i swear')
```

#### `child(name: string, ...colors: AnyColor[]): LoggerInstance`, `child(name, options): LoggerInstance`

```js
const db = log.child('db')        // namespaced under the parent
const pool = db.child('pool', Color.Cyan)
```

#### `time(label: string): (...data: any[]) => void`

```js
const done = log.time('build')
// ... work ...
done() // build: 1.23s
```

#### `with(fields: Record<string, unknown>): LoggerInstance`

```js
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`

```js
log.enabled('debug') // would log.debug(...) be written anywhere?
log.enabled()        // would a raw log(...) be written?
```

---
_Source: https://npm.io/package/@starkow/logger · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
