Skip to content

Formatting

Make your console logs pop and stay readable by leveraging ANSI escape codes. LogPot treats styling as just another layer of formatting, so you can mix colors, backgrounds, padding and more without extra ceremony.

type Colorizer = (text: string) => string
type ColorOrColorizer = string | Colorizer
  • Colorizer A function that wraps input text in ANSI codes.
  • ColorOrColorizer Either a space‑separated string of style tokens or your own transformer.

Colorize HTML strings.

import { getLogger } from 'logpot'
import { colorizeHTML } from '@logpot/printer'
getLogger().debug(colorizeHTML('<span class="tag">Hi</span>'))

Pass a configuration object { tag, attrKey, attrValue, attrEq, content } to override the default colors.

interface ColorConfig {
null: ColorOrColorizer
undefined: ColorOrColorizer
number: ColorOrColorizer
boolean: ColorOrColorizer
string: ColorOrColorizer
symbol: ColorOrColorizer
function: ColorOrColorizer
date: ColorOrColorizer
key: ColorOrColorizer
circular: ColorOrColorizer
default: ColorOrColorizer
colon: ColorOrColorizer
comma: ColorOrColorizer
bracket: ColorOrColorizer
custom: ColorOrColorizer
}
interface LogPotColorConfig extends Partial<ColorConfig> {
msg?: ColorOrColorizer
level?: ColorOrColorizer
time?: ColorOrColorizer
emoji?: ColorOrColorizer
}
  • ColorConfig: Assign colors to JS primitives & punctuation.
  • LogPotColorConfig: Override specific log elements (msg, level label, time, emoji).
type ConsoleTheme<Levels> = Record<LevelName<Levels> | '*', LogPotColorConfig>

Map each log level (plus '*' fallback) to its styling rules.


Customizing your logs happens in two layers:

  1. CommonOptions (shared by all kinds)
  2. Kind‑specific options (JSON Array, NDJSON, Envelope, Template)
interface CommonOptions<Levels> {
locale?: string | string[]
timeFormat?: 'epoch' | 'iso' | Intl.DateTimeFormatOptions
fieldMap?: Record<string, string>
gzip?: boolean
mergeMeta?: boolean
stringify?:
| 'simple'
| 'pretty'
| 'colorize'
| 'printer'
| ((value: unknown) => string)
printer?: {
theme?: Partial<ConsoleTheme<Levels>>
maxDepth?: number
indentString?: string
quotes?: string
objectFormatter?: Partial<ObjectFormatterConfig>
arrayFormatter?: Partial<ArrayFormatterConfig>
dateFormatter?: Partial<DateFormatterConfig>
}
}
  • locale: BCP‑47 tag(s) for dates.

  • timeFormat: 'epoch', 'iso' or custom Intl options.

  • fieldMap: Rename keys (msg→message, time→timestamp).

  • gzip: GZIP‑compress output.

  • mergeMeta: Inline all meta props at top level.

  • stringify:

    • 'simple'JSON.stringify
    • 'pretty'JSON.stringify(..., null, 2)
    • 'colorize' → ANSI‑colored printer
    • 'printer' → uncolored pretty‑printer
    • custom function
  • printer: Fine‑tune indentation, quoting and theme overrides.


Emit one big array:

formatter: { kind: 'json-array', /* + CommonOptions */ }

Use for batch exports or analytics pipelines.


Newline‑delimited JSON:

formatter: { kind: 'ndjson', delimiter: '\n', /* + CommonOptions */ }

Use for streaming into files, pipes, or HTTP endpoints.


Wrap your array under a key:

formatter: { kind: 'envelope', envelopeKey: 'events', /* + CommonOptions */ }

Use for protocols or APIs that expect a top‑level object.


Full control over every detail:

formatter: {
kind: 'template',
template: '{time} {level:bold padend 6} {emoji} {msg}\n{meta}',
emojis: { DEBUG: '🐞', WARN: '⚠️', ERROR: '' },
stringify: 'colorize',
theme: {
'*': {
key: '#6c6c6c',
},
DEBUG: {
msg: 'bg#3f260a #ff44aa doubleunderline',
},
INFO: {
msg: 'bg#3f260a #ff44aa doubleunderline',
},
},
}
  • Placeholders: {time}, {level}, {msg}, {meta}, or deep paths {meta.userId}
  • Inline modifiers: bold, underline, #ff00ff, bg#222, padend 20
  • Expressions: {meta.errorCode ?? 'N/A'}
  • Hooks: run JS on each placeholder

interface DateFormatterConfig {
method: 'ISO' | 'epoch' | 'custom'
locales?: string | string[]
options?: Intl.DateTimeFormatOptions
}
  • ISOnew Date().toISOString()
  • epoch → milliseconds since UNIX epoch
  • custom → use Intl.DateTimeFormat(locales, options)

interface ObjectFormatterConfig {
showBrackets: boolean
showCommas: boolean
sortKeys: (keys: string[], obj: Record<string, unknown>) => string[]
maxEntries: number
}
  • showBrackets / showCommas: include {} or ,
  • sortKeys: custom order function
  • maxEntries: truncate after N fields

  • maxInlineLength (default 40): max chars before multiline
  • maxInlineItems (default 10): max items inline
  • maxItems (default 100): max entries in multiline
  • trailingComma (default false)
  • overflowMessage: (len, rem) => string when truncated
  • shouldInline: custom hook to force inline
  • delimiters: { open, close }
  • separatorInline / separator
  • prefix: per‑item prefix (e.g. '- ' for YAML)
  • sparseArrayEmptyElement (default '<empty>')

formatter: {
kind: 'template',
stringify: 'colorize',
printer: {
quotes: '',
indentString: ' ',
objectFormatter: {
showBrackets: false,
showCommas: false,
maxEntries: Infinity,
},
arrayFormatter: {
open: '', close: '',
prefix: '- ',
separatorInline: ' ',
separator: '',
maxInlineLength: 0,
},
}
}
# Before (JSON)
{ "user": "alice", "permissions": ["read", "write"] }
# After (YAML‑style)
user: alice
permissions:
- read
- write

class Formatter<Levels> {
constructor(
options: FormatterOptions<Levels>,
levelDefinition: LevelDefinition<Levels>
)
// Render a batch of logs to string or Buffer
format(batch: Log<Levels>[]): string | Buffer
}
  • Chooses JSON / NDJSON / envelope / template based on kind
  • Applies field mapping, time formatting, coloring, and compression

Use any of these tokens (aliases shown in parentheses) in your ColorOrColorizer strings. You can also supply true‑color hex codes (#rrggbb) or background hex (bg#rrggbb).

TokenEffect
resetClear all styles
boldBold text
dim / faintFaint (reduced intensity)
italicItalic text
underlineUnderlined text
doubleunderlineDouble‑underlined
inverse / swapcolorsSwap foreground/background
hidden / concealHidden text
strikethrough / crossedoutStrike through
blinkBlinking text
framedEnclose in a box
overlinedOverline text
TokenEffect
blackBlack
redRed
greenGreen
yellowYellow
blueBlue
magentaMagenta
cyanCyan
whiteWhite
gray / grey / blackbrightBright black (gray)
redbrightBright red
greenbrightBright green
yellowbrightBright yellow
bluebrightBright blue
magentabrightBright magenta
cyanbrightBright cyan
whitebrightBright white
TokenEffect
bgblackBlack background
bgredRed background
bggreenGreen background
bgyellowYellow background
bgblueBlue background
bgmagentaMagenta background
bgcyanCyan background
bgwhiteWhite background
bggray / bggrey / bgblackbrightBright black background
bgredbrightBright red bg
bggreenbrightBright green bg
bgyellowbrightBright yellow bg
bgbluebrightBright blue bg
bgmagentabrightBright magenta bg
bgcyanbrightBright cyan bg
bgwhitebrightBright white bg
DirectiveArgEffectDefault Arg
padstartnLeft‑pad the text to width n.20
padendnRight‑pad the text to width n.20
centernCenter the text in a field of width n.20
maxnTruncate text to at most n characters (appending ).20
themekeyLookup theme[key] in your ConsoleTheme and apply its Colorizer.
lowerConvert to uppercase (ANSI escapes preserved).
lowerlLocale‑aware lowercase (ANSI escapes preserved).
upperConvert to uppercase (ANSI escapes preserved).
upperlLocale‑aware uppercase (ANSI escapes preserved).