debug vs winston vs pino vs loglevel vs log4js vs bunyan
JavaScript Logging Libraries for Frontend and Full-Stack Applications
debugwinstonpinologlevellog4jsbunyanSimilar Packages:
JavaScript Logging Libraries for Frontend and Full-Stack Applications

bunyan, debug, log4js, loglevel, pino, and winston are widely used JavaScript logging libraries that help developers track application behavior, diagnose issues, and monitor performance. While some were originally built for Node.js environments, several have evolved to support browser-based frontend use cases as well. These libraries differ significantly in architecture, performance characteristics, output format, extensibility, and suitability for client-side versus server-side contexts.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
debug423,973,45511,39442.8 kB842 months agoMIT
winston16,959,99724,184273 kB5222 months agoMIT
pino15,767,41316,839637 kB139a month agoMIT
loglevel12,185,1952,73086.2 kB18a year agoMIT
log4js6,973,2485,847160 kB973 years agoApache-2.0
bunyan2,572,0197,215-2945 years agoMIT

JavaScript Logging Libraries Compared: bunyan, debug, log4js, loglevel, pino, winston

Logging seems simple until you’re knee-deep in production incidents with no clear trail of what went wrong. The right logging library can mean the difference between a 5-minute fix and an all-nighter. But not all loggers are built alike — especially when you’re juggling frontend constraints like bundle size and browser compatibility alongside backend needs like performance and structured output.

Let’s break down how these six libraries handle real-world logging challenges.

🖥️ Browser Support: Where Can You Actually Use Them?

Not every logger plays nice in the browser. Some assume Node.js globals like process or filesystem access, which breaks in client-side code.

loglevel was built from the ground up for the browser. It’s tiny, uses console under the hood, and respects native devtools filtering. Perfect for SPAs or embedded widgets.

// loglevel: Simple browser logging
import log from 'loglevel';
log.setLevel('debug');
log.debug('User clicked button'); // Shows in browser console

winston and log4js offer official browser builds. Winston uses its transport system to route logs to console, while log4js provides appenders like browserConsole. Both work but add noticeable bundle weight.

pino has pino-browser, a separate package that mimics core behavior using console, but it’s opinionated about JSON formatting — which browsers don’t render beautifully by default.

bunyan has no official browser support. Attempts to shim it often fail due to its reliance on Node streams and synchronous disk writes.

debug works everywhere — it’s just a thin wrapper around console.log with namespace filtering. No build step needed.

⚡ Performance: How Much Does Logging Slow You Down?

In high-frequency scenarios (e.g., request logging in APIs), logger overhead matters.

pino is the speed king. It avoids object serialization during hot paths by using asynchronous flushing and string concatenation. Logs are written as newline-delimited JSON, ready for ingestion by tools like Fluentd or Loki.

// pino: Fast structured logging
const logger = require('pino')();
logger.info({ userId: 123 }, 'User logged in');
// Output: {"level":30,"time":1712345678901,"pid":12345,"hostname":"...","userId":123,"msg":"User logged in"}

bunyan is also performant in Node but slower than pino due to synchronous object creation and richer metadata by default.

winston and log4js are heavier because they support synchronous multi-transport dispatch (e.g., writing to file + sending to HTTP endpoint at once). This flexibility costs CPU cycles.

loglevel and debug are fast in the browser because they delegate entirely to console — but only if you disable logging in production (via minification or runtime checks).

📦 Structure vs. Readability: JSON Logs or Human-Friendly?

Do you want logs that machines parse easily or ones developers read directly?

pino and bunyan enforce structured JSON. Great for log aggregation, terrible for tailing files locally unless you pipe through their CLI formatters (pino-pretty, bunyan -o short).

# Pretty-print pino logs
node app.js | pino-pretty

winston, log4js, and loglevel default to human-readable strings but allow JSON formatting via options or formatters.

// winston: Switch between formats
const { createLogger, format, transports } = require('winston');
const logger = createLogger({
  format: format.combine(
    format.timestamp(),
    format.json() // or format.simple()
  ),
  transports: [new transports.Console()]
});

debug is purely human-readable — just plain strings with colored namespaces.

🔌 Extensibility: Transports, Formatters, and Plugins

Need to send logs to Slack, Datadog, or rotate files daily? That’s where transports and appenders come in.

winston leads here with a vast ecosystem of transports (winston-daily-rotate-file, winston-slack, etc.). Its architecture treats every output as a “transport,” making it trivial to log to multiple destinations.

log4js uses “appenders” with similar flexibility — you can chain them, filter by level, or write custom ones.

pino takes a Unix philosophy approach: do one thing well (emit JSON lines), then pipe to external tools. Integrations exist (e.g., pino-datadog), but they’re often separate processes, not in-process transports.

loglevel supports plugins for things like prefixing or localStorage persistence, but nothing for remote shipping.

debug has no extension mechanism — it’s intentionally minimal.

bunyan supports custom streams (its version of transports), but the ecosystem is smaller than Winston’s.

🧪 Development Experience: Filtering and Debugging

During local development, you want fine-grained control over what logs appear.

debug excels here. Set localStorage.debug = 'myapp:*' in the browser or DEBUG=myapp:* node app.js in Node to enable only relevant logs.

// debug: Namespace-based filtering
const log = require('debug')('myapp:auth');
log('Login attempt'); // Only shows if DEBUG includes 'myapp:auth'

loglevel lets you set global or individual logger levels at runtime — useful for enabling trace logs in a live browser session.

winston and log4js support per-logger levels but require programmatic changes or config reloads, which is clunkier for ad-hoc debugging.

pino and bunyan rely on external tools for filtering (e.g., grep or log shipper rules), which isn’t ideal during active development.

🛑 What About Deprecation or Maintenance?

None of these packages are officially deprecated. However, bunyan has seen minimal updates in recent years, and its author recommends pino for new projects. While still functional, it’s effectively in maintenance mode.

🤝 Key Similarities Across All Libraries

Despite their differences, these loggers share common ground:

1. Support Standard Log Levels

All provide at least error, warn, info, and debug (or equivalent). This enables consistent severity-based filtering.

// Common pattern across libraries
logger.error('Database connection failed');
logger.warn('Deprecated API used');
logger.info('Server started');
logger.debug('Request payload:', payload);

2. Allow Custom Metadata

You can attach context like user IDs, request IDs, or timestamps to enrich logs.

// winston example
logger.info('Payment processed', { userId: 456, amount: 29.99 });

// pino example
logger.info({ userId: 456, amount: 29.99 }, 'Payment processed');

3. Enable Conditional Logging

All respect log level thresholds — calls below the current level are no-ops, minimizing runtime cost.

4. Work with Modern Toolchains

Each supports ES modules (either natively or via bundlers like Webpack or Vite), TypeScript definitions, and tree-shaking where applicable.

5. Integrate with Observability Stacks

Whether you use ELK, Grafana Loki, Datadog, or Splunk, structured logs from any of these can feed into your pipeline — though pino and bunyan require less transformation due to native JSON.

📊 Summary: When to Use Which Logger

ScenarioBest ChoiceWhy
Frontend-only app, small bundleloglevelTiny, browser-native, clean console output
Library author needing dev-time debug logsdebugZero-config, namespace filtering, universal support
High-performance Node.js servicepinoBlazing fast, structured JSON, async-friendly
Full-stack app needing consistencywinstonUnified API across environments, rich transport ecosystem
Migrating from Java/Log4jlog4jsFamiliar concepts (appenders, categories), config-driven
Legacy Node.js project (avoid new)bunyanStill works, but prefer pino for new work

💡 Final Recommendation

For new frontend projects, start with loglevel — it’s purpose-built for the browser and gets out of your way. If you’re building a library, sprinkle in debug for optional developer diagnostics.

For Node.js backends, pino is the modern default for performance-critical services. Choose winston if you need maximum flexibility in routing logs to multiple destinations without external tooling.

Avoid mixing more than two loggers in one codebase — it creates inconsistency and complicates log aggregation. Pick one primary logger and stick with it across your stack where possible.

How to Choose: debug vs winston vs pino vs loglevel vs log4js vs bunyan
  • debug:

    Choose debug when you need a minimal, zero-dependency utility for conditional logging during development, especially for library authors or internal debugging workflows. It shines with its simple namespace-based filtering via the DEBUG environment variable but lacks production-grade features like log levels, transports, or structured output—so don’t use it as your primary application logger in production.

  • winston:

    Choose winston if you need a highly configurable, transport-agnostic logging system that works consistently across Node.js and browser environments. Its modular architecture supports multiple outputs (console, file, HTTP, etc.) simultaneously and allows custom formatting and filtering. It’s a solid default choice for full-stack apps but may be overkill for simple frontend-only logging needs.

  • pino:

    Choose pino when performance and structured JSON logging are critical—especially in high-throughput Node.js services. Its asynchronous, stream-based design minimizes overhead, and it integrates well with log aggregation pipelines. While browser support exists via pino-browser, it’s less ergonomic than dedicated frontend loggers; best paired with a backend logging strategy rather than used standalone in the browser.

  • loglevel:

    Choose loglevel for frontend applications where you need a tiny, browser-first logging solution with standard log levels (trace to error) and plugin support. It’s ideal when bundle size matters, you want clean console output, and you don’t need structured logging or server-side features. Avoid it if you require JSON output, log rotation, or advanced transport mechanisms.

  • log4js:

    Choose log4js if you’re migrating from Java’s Log4j ecosystem or need a familiar hierarchical logger with appenders, categories, and configuration-driven behavior. It supports both Node.js and browser environments and offers decent flexibility, but its API can feel verbose compared to modern alternatives, and performance isn’t optimized for high-throughput scenarios.

  • bunyan:

    Choose bunyan if you're working in a Node.js environment and need structured JSON logging with strong CLI tooling for log inspection. It’s not ideal for browser use due to its Node-centric design and lack of lightweight browser builds. Avoid it for frontend-only projects or when human-readable console output is preferred during development.

README for debug

debug

OpenCollective OpenCollective

A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers.

Installation

$ npm install debug

Usage

debug exposes a function; simply pass this function the name of your module, and it will return a decorated version of console.error for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.

Example app.js:

var debug = require('debug')('http')
  , http = require('http')
  , name = 'My App';

// fake app

debug('booting %o', name);

http.createServer(function(req, res){
  debug(req.method + ' ' + req.url);
  res.end('hello\n');
}).listen(3000, function(){
  debug('listening');
});

// fake worker of some kind

require('./worker');

Example worker.js:

var a = require('debug')('worker:a')
  , b = require('debug')('worker:b');

function work() {
  a('doing lots of uninteresting work');
  setTimeout(work, Math.random() * 1000);
}

work();

function workb() {
  b('doing some work');
  setTimeout(workb, Math.random() * 2000);
}

workb();

The DEBUG environment variable is then used to enable these based on space or comma-delimited names.

Here are some examples:

screen shot 2017-08-08 at 12 53 04 pm screen shot 2017-08-08 at 12 53 38 pm screen shot 2017-08-08 at 12 53 25 pm

Windows command prompt notes

CMD

On Windows the environment variable is set using the set command.

set DEBUG=*,-not_this

Example:

set DEBUG=* & node app.js
PowerShell (VS Code default)

PowerShell uses different syntax to set environment variables.

$env:DEBUG = "*,-not_this"

Example:

$env:DEBUG='app';node app.js

Then, run the program to be debugged as usual.

npm script example:

  "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",

Namespace Colors

Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to.

Node.js

In Node.js, colors are enabled when stderr is a TTY. You also should install the supports-color module alongside debug, otherwise debug will only use a small handful of basic colors.

Web Browser

Colors are also enabled on "Web Inspectors" that understand the %c formatting option. These are WebKit web inspectors, Firefox (since version 31) and the Firebug plugin for Firefox (any version).

Millisecond diff

When actively developing an application it can be useful to see when the time spent between one debug() call and the next. Suppose for example you invoke debug() before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.

When stdout is not a TTY, Date#toISOString() is used, making it more useful for logging the debug information as shown below:

Conventions

If you're using this in one or more of your libraries, you should use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you should prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.

Wildcards

The * character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with DEBUG=connect:bodyParser,connect:compress,connect:session, you may simply do DEBUG=connect:*, or to run everything using this module simply use DEBUG=*.

You can also exclude specific debuggers by prefixing them with a "-" character. For example, DEBUG=*,-connect:* would include all debuggers except those starting with "connect:".

Environment Variables

When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging:

NamePurpose
DEBUGEnables/disables specific debugging namespaces.
DEBUG_HIDE_DATEHide date from debug output (non-TTY).
DEBUG_COLORSWhether or not to use colors in the debug output.
DEBUG_DEPTHObject inspection depth.
DEBUG_SHOW_HIDDENShows hidden properties on inspected objects.

Note: The environment variables beginning with DEBUG_ end up being converted into an Options object that gets used with %o/%O formatters. See the Node.js documentation for util.inspect() for the complete list.

Formatters

Debug uses printf-style formatting. Below are the officially supported formatters:

FormatterRepresentation
%OPretty-print an Object on multiple lines.
%oPretty-print an Object all on a single line.
%sString.
%dNumber (both integer and float).
%jJSON. Replaced with the string '[Circular]' if the argument contains circular references.
%%Single percent sign ('%'). This does not consume an argument.

Custom formatters

You can add custom formatters by extending the debug.formatters object. For example, if you wanted to add support for rendering a Buffer as hex with %h, you could do something like:

const createDebug = require('debug')
createDebug.formatters.h = (v) => {
  return v.toString('hex')
}

// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
//   foo this is hex: 68656c6c6f20776f726c6421 +0ms

Browser Support

You can build a browser-ready script using browserify, or just use the browserify-as-a-service build, if you don't want to build it yourself.

Debug's enable state is currently persisted by localStorage. Consider the situation shown below where you have worker:a and worker:b, and wish to debug both. You can enable this using localStorage.debug:

localStorage.debug = 'worker:*'

And then refresh the page.

a = debug('worker:a');
b = debug('worker:b');

setInterval(function(){
  a('doing some work');
}, 1000);

setInterval(function(){
  b('doing some work');
}, 1200);

In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by debug if the "Verbose" log level is enabled.

Output streams

By default debug will log to stderr, however this can be configured per-namespace by overriding the log method:

Example stdout.js:

var debug = require('debug');
var error = debug('app:error');

// by default stderr is used
error('goes to stderr!');

var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');

// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');

Extend

You can simply extend debugger

const log = require('debug')('auth');

//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');

log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello

Set dynamically

You can also enable debug dynamically by calling the enable() method :

let debug = require('debug');

console.log(1, debug.enabled('test'));

debug.enable('test');
console.log(2, debug.enabled('test'));

debug.disable();
console.log(3, debug.enabled('test'));

print :

1 false
2 true
3 false

Usage :
enable(namespaces)
namespaces can include modes separated by a colon and wildcards.

Note that calling enable() completely overrides previously set DEBUG variable :

$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false

disable()

Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with.

For example:

let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);

Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical.

Checking whether a debug target is enabled

After you've created a debug instance, you can determine whether or not it is enabled by checking the enabled property:

const debug = require('debug')('http');

if (debug.enabled) {
  // do stuff...
}

You can also manually toggle this property to force the debug instance to be enabled or disabled.

Usage in child processes

Due to the way debug detects if the output is a TTY or not, colors are not shown in child processes when stderr is piped. A solution is to pass the DEBUG_COLORS=1 environment variable to the child process.
For example:

worker = fork(WORKER_WRAP_PATH, [workerPath], {
  stdio: [
    /* stdin: */ 0,
    /* stdout: */ 'pipe',
    /* stderr: */ 'pipe',
    'ipc',
  ],
  env: Object.assign({}, process.env, {
    DEBUG_COLORS: 1 // without this settings, colors won't be shown
  }),
});

worker.stderr.pipe(process.stderr, { end: false });

Authors

  • TJ Holowaychuk
  • Nathan Rajlich
  • Andrew Rhyne
  • Josh Junon

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]

Sponsors

Become a sponsor and get your logo on our README on Github with a link to your site. [Become a sponsor]

License

(The MIT License)

Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> Copyright (c) 2018-2021 Josh Junon

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.