Skip to content

munesoft/logx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@munesoft/logx

A tiny, zero-config logger for Node.js and browser.
Structured, beautiful, and fast — without the complexity.

npm license bundle size


🚀 Why logx?

Most logging libraries are too complex, too heavy, or require pages of setup.

logx is:

  • Simple — feels exactly like console.log
  • Fast — 1–3M ops/s, zero heavy dependencies
  • Structured — every log is internally a typed object
  • Beautiful — colored output, clean stack traces, readable key=val pairs
  • Universal — Node.js + browser, ESM + CJS

⚡ Quick Start

npm install @munesoft/logx
import logx from '@munesoft/logx';

logx('User created', { id: 123 });
// ✔ User created  id=123

Zero setup. Just import and go.


🔥 Features

Feature Description
Structured logging Every log carries typed metadata
Log levels info, warn, error, debug with smart defaults
Colored output ANSI colors in Node, %c styling in browser
JSON mode Emit newline-delimited JSON for log aggregators
Child loggers Bind persistent context to a logger instance
Transports Route logs to any destination
Filters Programmatically suppress log levels
Grouping console.group-style nesting
Error handling Auto-detect Error objects, format stack traces
Circular refs Safe serialization — never throws
sprintf formatting logx('User %s created', name)
Zero config Works out of the box
Tree-shakeable ESM, pure module
TypeScript Full .d.ts included

📊 Examples

Basic

logx('Hello world');
// ✔ Hello world

With Data

logx('User created', { id: 1, role: 'admin' });
// ✔ User created  id=1 role=admin

Log Levels

logx.info('Server started', { port: 3000 });
// ✔ Server started  port=3000

logx.warn('Rate limit approaching', { current: 90, limit: 100 });
// ⚠ Rate limit approaching  current=90 limit=100

logx.error('Database error', new Error('ECONNREFUSED'));
// ✖ Database error
//   Error: ECONNREFUSED
//     at ...

logx.debug('Cache miss', { key: 'users:123' });
// ◆ Cache miss  key=users:123

JSON Output

Perfect for production log aggregation (Datadog, Loki, CloudWatch, etc.):

logx.json('User created', { id: 1 });
// {"level":"info","message":"User created","timestamp":1714230000,"id":1}

Enable JSON mode globally:

logx.config({ json: true });

Child Loggers

Bind context to a logger — every message from it automatically includes that context:

const apiLog = logx.child({ service: 'api', version: '2' });

apiLog('Request received', { path: '/users', method: 'GET' });
// ✔ Request received  service=api version=2 path=/users method=GET

apiLog.warn('Slow response', { ms: 2300 });
// ⚠ Slow response  service=api version=2 ms=2300

Nest child loggers:

const reqLog = apiLog.child({ requestId: 'abc-123' });
reqLog('Processing');
// ✔ Processing  service=api version=2 requestId=abc-123

Error Handling

Pass Error objects directly — logx detects and formats them automatically:

try {
  await db.query(sql);
} catch (err) {
  logx.error('Query failed', err, { sql });
}
// ✖ Query failed  sql=SELECT...
//   Error: connection timeout
//     at Database.query (db.js:45:12)
//     at ...

Sprintf-Style Formatting

logx('User %s logged in from %s', username, ip);
logx('Processed %d items in %dms', count, duration);

Transports

Route logs to external systems:

logx.use((entry) => {
  fetch('/api/logs', {
    method: 'POST',
    body: JSON.stringify(entry),
  });
});

Return false to suppress default console output:

logx.use((entry) => {
  myLogger.write(entry);
  return false; // don't also print to console
});

Filters

// Suppress debug logs in staging
logx.filter((level) => level !== 'debug');

// Only log errors and warnings  
logx.filter((level) => ['error', 'warn'].includes(level));

Grouping

logx.group('Auth Flow', () => {
  logx('Checking credentials');
  logx('Validating token', { userId: 7 });
  logx('Session created');
});

Configuration

logx.config({
  level:     'debug',   // 'silent' | 'error' | 'warn' | 'info' | 'debug'
  pretty:    true,      // formatted output (vs raw)
  json:      false,     // force JSON mode
  timestamp: true,      // include timestamp in every log
  silent:    false,     // suppress all output
});

One-call silence:

logx({ silent: true });

Async Context

Attach context that will appear on all subsequent logs (useful in request middleware):

app.use((req, res, next) => {
  logx.context({ requestId: req.headers['x-request-id'] });
  next();
});

🆚 Comparison

Feature console.log pino winston logx
Zero config
Structured
Colored output requires plugin requires plugin
JSON mode
Child loggers
Browser support
TypeScript
Bundle size 0 kb ~50 kb ~100 kb < 5 kb
Setup required none low high none

📦 Install & Import

npm install @munesoft/logx
# or
yarn add @munesoft/logx

ESM:

import logx from '@munesoft/logx';

CJS:

const logx = require('@munesoft/logx');

Browser (CDN):

<script type="module">
  import logx from 'https://cdn.skypack.dev/@munesoft/logx';
  logx('Hello from browser!');
</script>

⚙️ Environment Awareness

logx automatically adapts:

Environment Default Level Notes
NODE_ENV=development debug All levels visible
NODE_ENV=production info Debug suppressed
NO_COLOR=1 any ANSI colors disabled
Browser (localhost) debug Dev mode detected
Browser (production) info Minimal output

🏎️ Performance

Benchmarked on Node.js 22, Apple M-series:

logx("Hello world")               1,006,100 ops/s   0.99 µs/op
logx("Msg", { id: 1 })            1,178,384 ops/s   0.85 µs/op
logx.info("Info", { x: 1 })       2,315,195 ops/s   0.43 µs/op
logx.json("Event", { ok: true })  1,507,092 ops/s   0.66 µs/op
child("Msg", { id: 1 })           2,290,502 ops/s   0.44 µs/op
logx with circular ref            1,582,889 ops/s   0.63 µs/op

🏗️ Architecture

src/
├── core/       # Main logging engine, config, child loggers, transports
├── format/     # Pretty (ANSI) + JSON + browser (%c) formatters
├── color/      # Zero-dependency ANSI color utilities
├── levels/     # Level constants and comparison logic  
├── utils/      # sprintf, safe serialization, env detection, timestamps
└── browser/    # Browser-specific console adapter

No runtime dependencies. Zero external packages.


🧪 Testing

npm test       # 27 unit tests
npm run bench  # performance benchmarks

📄 License

MIT © munesoft


🔍 Keywords

nodejs logger, javascript logger, browser logger, structured logging, zero-config logger, console.log alternative, lightweight logger, pino alternative, winston alternative, fast logger, json logger, colored terminal output

About

Tiny zero-config JavaScript logger for Node.js & browser. Structured logging, colored output, JSON mode, child loggers & TypeScript support. No setup required.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors