@nan0web/log
v1.1.0
Published
A cross-platform Logger class that wraps console methods for both Node.js and browsers with consistent interface and streaming support.
Maintainers
Readme
@nan0web/log
|Package name|Status|Documentation|Test coverage|Features|Npm version|
|---|---|---|---|---|---|
|@nan0web/log |🟢 98.9% |🧪 English 🏴Українською 🇺🇦 |🟢 94.2% |✅ d.ts 📜 system.md 🕹️ playground |1.0.0 |
A cross-platform Logger class that wraps console methods for both Node.js and browsers with consistent interface and streaming support.
Description
The @nan0web/log package provides a minimal yet powerful foundation for logging systems.
Core classes:
Logger— main logger class with levels, icons, colors, time and streaming supportLogConsole— wraps console methods for consistent cross-platform loggingLoggerFormat— defines format for a logger level with icon, color and backgroundNoLogger— captures logs in memory, perfect for testingNoConsole— captures console output in memory, perfect for testing
These classes are perfect for building CLI tools, debugging layers, structured logs, and streaming data to files or external services.
Installation
How to install with npm?
npm install @nan0web/logHow to install with pnpm?
pnpm add @nan0web/logHow to install with yarn?
yarn add @nan0web/logUsage
Basic Logger
Logger can be instantiated with a level or options and logs everything below that level
How to create a Logger instance with level?
import Logger from '@nan0web/log'
const logger = new Logger('debug')
logger.info(typeof logger.debug) // ← function
logger.info(logger.level) // ← debugHow to create a Logger instance with options?
import Logger from '@nan0web/log'
const logger = new Logger({
level: 'info',
icons: true,
chromo: true,
time: true,
})
logger.info("Hello with options") // ← TIME-HH-IIT... ℹ Hello with optionsCustom Formats
Logger supports custom formats for different levels
How to use custom formats for different levels?
import Logger from '@nan0web/log'
const logger = new Logger({
level: "debug",
icons: true,
formats: [
["debug", { icon: "🔍", color: Logger.CYAN }],
["info", { icon: "ℹ️ ", color: Logger.GREEN }],
["warn", { icon: "⚠️ ", color: Logger.YELLOW }],
["error", { icon: "❌", color: Logger.RED }],
["success", { icon: "✅", color: Logger.GREEN }],
]
})
logger.debug("Debug message") // ← \x1b[36m🔍 Debug message\x1b[0m
logger.info("Info message") // ← \x1b[32mℹ️ Info message\x1b[0m
logger.warn("Warning message") // ← \x1b[33m⚠️ Warning message\x1b[0m
logger.error("Error message") // ← \x1b[31m❌ Error message\x1b[0m
logger.success("Success message") // ← \x1b[32m✅ Success message\x1b[0mStreaming Logs
Logger supports streaming logs to files or external services
How to stream logs to a file?
import Logger from '@nan0web/log'
let streamOutput = ""
const logger = new Logger({
stream: async (message) => {
streamOutput += message
}
})
logger.broadcast("Streamed message")
// Wait a bit for async operations
await new Promise(resolve => setTimeout(resolve, 10))
console.log(streamOutput) // ← Streamed messageMemory Logging with NoLogger
NoLogger captures logs in memory instead of printing them, perfect for testing
How to capture logs in memory with NoLogger?
import { NoLogger } from '@nan0web/log'
const logger = new NoLogger({ level: "debug" })
logger.debug("Debug message")
logger.info("Info message")
logger.warn("Warning message")
logger.error("Error message")
logger.success("Success message")
const logs = logger.output()
console.log(logs) // ← [ [ "debug", "Debug message" ], [ "info", "Info message" ], ... ]Advanced Features
Logger includes useful helpers for formatting, tables, progress, etc.
How to create and display formatted tables?
import Logger from '@nan0web/log'
const logger = new Logger()
const data = [
{ name: "John", age: 30, city: "New York" },
{ name: "Jane", age: 25, city: "Los Angeles" },
{ name: "Bob", age: 35, city: "Chicago" }
]
// Capture table output by mocking console methods
logger.table(data, ["name", "age", "city"], { padding: 2, border: 1 })
// ------------------------
// name age city
// John 30 New York
// Jane 25 Los Angeles
// Bob 35 Chicago
// ------------------------How to style text with colors and background?
import Logger from '@nan0web/log'
const styled = Logger.style("Styled text", {
color: Logger.MAGENTA,
bgColor: "white"
})
console.info(styled) // ← \x1b[35m\x1b[47mStyled text\x1b[0mHow to work with cursor and clear lines for progress?
import Logger from '@nan0web/log'
const logger = new Logger()
logger.info(logger.cursorUp(2)) // ← \x1b[2A
logger.info(logger.cursorDown(1)) // ← \x1b[1B
logger.info(logger.clearLine()) // ← \x1b[2K\rPrefix Option
Logger can prepend a custom prefix to every log line.
How to use Logger.prefix option?
const logger = new Logger({ prefix: "PREFIX> " })
logger.info("Message with prefix") // ← PREFIX> Message with prefixAPI
Logger
Properties
level– minimum log level to output (debug|info|warn|error|silent)console– Console instance used for outputicons– whether to show iconschromo– whether to apply colorstime– format for timestamps (default: false)spent– whether to log execution time differences (default: false)stream– function for output streaming (default: null)formats– map of formats for different log levels
Methods
debug(...args)– log debug messageinfo(...args)– log info messagewarn(...args)– log warning messageerror(...args)– log error messagesuccess(...args)– log success message (uses info channel)log(...args)– log generic messagesetFormat(target, opts)– set format for a log levelsetStream(streamFunction)– define stream function for outputtable(data, columns, options)– format and log table datawrite(str)– write string directly to stdoutcursorUp(lines)– move cursor up in terminalcursorDown(lines)– move cursor down in terminalclear()– clear the consoleclearLine()– clear the current linegetWindowSize()– get terminal size [columns, rows]cut(str, width)– cut string to terminal widthstatic from(input)– create Logger instance from string or optionsstatic detectLevel(argv)– detect log level from command line argsstatic createFormat(name, value)– create LoggerFormat from inputstatic style(value, styleOptions)– style a value with colorsstatic stripANSI(str)– remove ANSI codes from stringstatic progress(i, len, fixed)– calculate progress percentagestatic spent(checkpoint, fixed)– calculate time since checkpointstatic bar(i, len, width, char, space)– create progress bar string
LogConsole
Properties
console– the underlying console instanceprefix– prefix data for every log
Methods
debug(...args)– log debug messageinfo(...args)– log info messagewarn(...args)– log warning messageerror(...args)– log error messagelog(...args)– log generic messageclear()– clear the consoleassert(condition, ...args)– assert a conditioncount(label)– log count of calls with labelcountReset(label)– reset counter for labeldir(obj)– display object propertiesdirxml(obj)– display object treegroup(...args)– create inline groupgroupCollapsed(...args)– create collapsed groupgroupEnd()– exit current groupprofile(label)– start profileprofileEnd(label)– end profiletime(label)– start timertimeStamp(label)– log timestamptimeEnd(label)– stop timer and log elapsed timetimeLog(label)– log current timer valuetable(data, columns)– display tabular datatrace()– log stack trace
LoggerFormat
Properties
icon– icon stringcolor– ANSI color codebgColor– ANSI background color code
Methods
static from(input)– create format from object or existing instance
NoLogger
Extends Logger.
Properties
console– NoConsole instance that captures output
Methods
output()– return captured logs
NoConsole
Properties
silent– whether to suppress all output
Methods
debug(...args)– capture debug loginfo(...args)– capture info logwarn(...args)– capture warning logerror(...args)– capture error loglog(...args)– capture generic logclear()– clear captured logsoutput(type)– return captured logs (all or filtered by type)static from(input)– create or return NoConsole instance
Java•Script
Uses d.ts files for autocompletion
CLI Playground
How to run playground script?
# Clone the repository and run the CLI playground
git clone https://github.com/nan0web/log.git
cd log
npm install
npm run playContributing
How to contribute? - check here
License
How to license ISC? - check here
