pretty-logx 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ All notable changes to `pretty-logx` will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2024-01-15
9
+
10
+ ### Added
11
+
12
+ - Initial release of `pretty-logx`
13
+ - Six log levels: `trace`, `debug`, `info`, `warn`, `error`, `fatal`
14
+ - Beautiful colored terminal output with ANSI colors
15
+ - Short (`HH:MM:SS.mmm`) and ISO 8601 timestamp formats
16
+ - JSON mode for structured production logging
17
+ - Namespace support for tagging log sources
18
+ - Child loggers with inherited bindings
19
+ - Pretty error stack trace formatting
20
+ - Structured logging with object bindings (bindings-first calling convention)
21
+ - Level predicates (`isDebugEnabled`, `isInfoEnabled`, etc.)
22
+ - Runtime configuration via `configure()` and `level` setter
23
+ - Safe circular reference detection and serialization
24
+ - BigInt serialization support
25
+ - `NO_COLOR` environment variable support (https://no-color.org/)
26
+ - `FORCE_COLOR` environment variable support
27
+ - Automatic TTY color detection
28
+ - Custom write function support
29
+ - Error routing: `error`/`fatal` → `stderr`, rest → `stdout`
30
+ - ESM and CommonJS dual package
31
+ - Full TypeScript types and autocomplete
32
+ - Zero runtime dependencies
33
+ - Node.js 18+ compatibility
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 pretty-logx contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,157 @@
1
- # Temporary Holding Version
1
+ # pretty-logx
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A lightweight, beautiful, TypeScript-first logging library for Node.js.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/pretty-logx.svg)](https://www.npmjs.com/package/pretty-logx)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+ [![Node.js >= 18](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org)
8
+
9
+ ## Features
10
+
11
+ - 🎨 **Colored terminal output** with timestamps
12
+ - 📊 **6 log levels**: `trace`, `debug`, `info`, `warn`, `error`, `fatal`
13
+ - 🏭 **JSON mode** for structured production logging
14
+ - 🔖 **Namespaces** for tagging log sources
15
+ - 👶 **Child loggers** with inherited bindings
16
+ - 🐛 **Pretty error stack traces**
17
+ - 📦 **Structured logging** with object bindings
18
+ - 🎛️ **Configurable levels and colors**
19
+ - 🚫 **NO_COLOR** and **FORCE_COLOR** support
20
+ - 🔄 **Safe circular reference handling**
21
+ - 📝 **TypeScript-first** with full type inference
22
+ - 📦 **ESM + CommonJS** dual package
23
+ - ⚡ **Zero runtime dependencies**
24
+ - 🟢 **Node.js 18+**
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install pretty-logx
30
+ ```
31
+
32
+ ## Quick Start
33
+
34
+ ```ts
35
+ import { createLogger } from 'pretty-logx';
36
+
37
+ const log = createLogger({ level: 'debug', namespace: 'app' });
38
+
39
+ log.info('Server started', { port: 3000 });
40
+ log.debug({ query: 'SELECT * FROM users', duration: '12ms' }, 'DB query');
41
+ log.error({ err: new Error('Connection failed') }, 'Database error');
42
+ ```
43
+
44
+ ## API
45
+
46
+ ### `createLogger(config?)`
47
+
48
+ Creates a new logger instance.
49
+
50
+ ```ts
51
+ const log = createLogger({
52
+ level: 'info', // Minimum log level (default: 'info')
53
+ json: false, // JSON mode for production (default: false)
54
+ namespace: 'myapp', // Optional namespace prefix
55
+ timestamp: true, // Include timestamps (default: true)
56
+ timestampFormat: 'short', // 'iso' | 'short' | 'none' (default: 'short')
57
+ colors: true, // Override color auto-detection
58
+ write: (msg, level) => process.stdout.write(msg + '\n'), // Custom writer
59
+ });
60
+ ```
61
+
62
+ ### Log Methods
63
+
64
+ All log methods accept two calling conventions:
65
+
66
+ ```ts
67
+ // Message only
68
+ log.info('Hello world');
69
+
70
+ // Message + extra data
71
+ log.info('Request complete', { status: 200 });
72
+
73
+ // Bindings object first (recommended for structured logging)
74
+ log.info({ requestId: 'abc', userId: 42 }, 'User logged in');
75
+
76
+ // Error logging
77
+ log.error({ err: new Error('oops') }, 'Something failed');
78
+ log.error('Request failed', new Error('Timeout'));
79
+ ```
80
+
81
+ Available methods: `trace`, `debug`, `info`, `warn`, `error`, `fatal`
82
+
83
+ ### Level Predicates
84
+
85
+ ```ts
86
+ if (log.isDebugEnabled) {
87
+ log.debug('Expensive debug info', computeDebugInfo());
88
+ }
89
+ ```
90
+
91
+ Predicates: `isTraceEnabled`, `isDebugEnabled`, `isInfoEnabled`, `isWarnEnabled`, `isErrorEnabled`, `isFatalEnabled`
92
+
93
+ ### Child Loggers
94
+
95
+ ```ts
96
+ const reqLog = log.child({ requestId: 'req-123' });
97
+ reqLog.info('Processing'); // Includes requestId automatically
98
+
99
+ // Override config in child
100
+ const quietChild = log.child({}, { level: 'warn' });
101
+ ```
102
+
103
+ ### JSON Mode (Production)
104
+
105
+ ```ts
106
+ const log = createLogger({ json: true, level: 'info' });
107
+ log.info({ userId: 42 }, 'Login');
108
+ // Output: {"level":"info","levelValue":30,"time":"2024-01-15T12:00:00.000Z","msg":"Login","userId":42}
109
+ ```
110
+
111
+ ### Runtime Configuration
112
+
113
+ ```ts
114
+ log.level = 'debug'; // Change level
115
+ log.configure({ json: true, level: 'warn' }); // Multiple options at once
116
+ ```
117
+
118
+ ### Color Control
119
+
120
+ ```ts
121
+ import { setColorsEnabled } from 'pretty-logx';
122
+ setColorsEnabled(false); // Disable colors globally
123
+
124
+ // Or via environment:
125
+ // NO_COLOR=1 → disables colors
126
+ // FORCE_COLOR=1 → enables colors even in non-TTY
127
+ ```
128
+
129
+ ## Log Levels
130
+
131
+ | Level | Value | Use Case |
132
+ |---------|-------|---------------------------------|
133
+ | `trace` | 10 | Extremely detailed debugging |
134
+ | `debug` | 20 | Debug information |
135
+ | `info` | 30 | Normal operational messages |
136
+ | `warn` | 40 | Warnings, recoverable issues |
137
+ | `error` | 50 | Errors, failures |
138
+ | `fatal` | 60 | Critical failures |
139
+ | `silent`| ∞ | Suppress all output |
140
+
141
+ ## TypeScript
142
+
143
+ Full TypeScript support with strict types:
144
+
145
+ ```ts
146
+ import type { LoggerConfig, LogLevelName, LogRecord } from 'pretty-logx';
147
+ ```
148
+
149
+ ## CommonJS Support
150
+
151
+ ```js
152
+ const { createLogger } = require('pretty-logx');
153
+ ```
154
+
155
+ ## License
156
+
157
+ [MIT](LICENSE) © 2024
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Log levels for pretty-logx.
3
+ * Lower numbers = more verbose.
4
+ */
5
+ declare const LogLevel: {
6
+ readonly trace: 10;
7
+ readonly debug: 20;
8
+ readonly info: 30;
9
+ readonly warn: 40;
10
+ readonly error: 50;
11
+ readonly fatal: 60;
12
+ readonly silent: number;
13
+ };
14
+ type LogLevelName = keyof typeof LogLevel;
15
+ type LogLevelValue = (typeof LogLevel)[LogLevelName];
16
+ declare function isLogLevelName(value: unknown): value is LogLevelName;
17
+ declare function getLevelValue(level: LogLevelName): number;
18
+ declare function getLevelName(value: number): LogLevelName | undefined;
19
+
20
+ /**
21
+ * Detect whether colors should be enabled.
22
+ * Checks: NO_COLOR env var, FORCE_COLOR env var, TTY availability.
23
+ */
24
+ declare function detectColorSupport(): boolean;
25
+ declare function isColorsEnabled(): boolean;
26
+ declare function setColorsEnabled(enabled: boolean): void;
27
+
28
+ /**
29
+ * Configuration for creating a logger.
30
+ */
31
+ interface LoggerConfig {
32
+ /** Minimum level to log. Defaults to 'info'. */
33
+ level?: LogLevelName;
34
+ /** Enable JSON mode (structured logging for production). */
35
+ json?: boolean;
36
+ /** Namespace/name prefix for this logger. */
37
+ namespace?: string | undefined;
38
+ /** Whether to include timestamps. Defaults to true. */
39
+ timestamp?: boolean;
40
+ /** Timestamp format. Defaults to 'short'. */
41
+ timestampFormat?: 'iso' | 'short' | 'none';
42
+ /** Enable/disable colors. Auto-detected by default. */
43
+ colors?: boolean;
44
+ /** Custom write function. Defaults to process.stdout/stderr. */
45
+ write?: (output: string, level: LogLevelName) => void;
46
+ }
47
+ /**
48
+ * Structured log record for JSON mode.
49
+ */
50
+ interface LogRecord {
51
+ level: LogLevelName;
52
+ levelValue: LogLevelValue;
53
+ time: string;
54
+ msg: string;
55
+ namespace?: string;
56
+ err?: unknown;
57
+ [key: string]: unknown;
58
+ }
59
+ /**
60
+ * Arguments to a log method: message + optional bindings.
61
+ */
62
+ type LogArgs = [message: string] | [message: string, ...meta: unknown[]] | [bindings: object, message: string];
63
+ /**
64
+ * Core Logger class.
65
+ */
66
+ declare class Logger {
67
+ private _level;
68
+ private _levelValue;
69
+ private _json;
70
+ private _namespace;
71
+ private _timestamp;
72
+ private _timestampFormat;
73
+ private _write;
74
+ private _bindings;
75
+ constructor(config?: LoggerConfig, parentBindings?: Record<string, unknown>);
76
+ get level(): LogLevelName;
77
+ set level(level: LogLevelName);
78
+ get levelValue(): number;
79
+ get namespace(): string | undefined;
80
+ get isJsonMode(): boolean;
81
+ get isTraceEnabled(): boolean;
82
+ get isDebugEnabled(): boolean;
83
+ get isInfoEnabled(): boolean;
84
+ get isWarnEnabled(): boolean;
85
+ get isErrorEnabled(): boolean;
86
+ get isFatalEnabled(): boolean;
87
+ private _log;
88
+ private _writeJson;
89
+ private _writePretty;
90
+ trace(...args: unknown[]): void;
91
+ debug(...args: unknown[]): void;
92
+ info(...args: unknown[]): void;
93
+ warn(...args: unknown[]): void;
94
+ error(...args: unknown[]): void;
95
+ fatal(...args: unknown[]): void;
96
+ /**
97
+ * Create a child logger with additional bindings and optional config overrides.
98
+ */
99
+ child(bindingsOrConfig: Record<string, unknown>, config?: Omit<LoggerConfig, 'namespace'>): Logger;
100
+ /**
101
+ * Create a namespaced child logger.
102
+ */
103
+ ns(namespace: string): Logger;
104
+ /**
105
+ * Configure this logger instance.
106
+ */
107
+ configure(config: Partial<LoggerConfig>): void;
108
+ }
109
+ /**
110
+ * Create a new logger instance.
111
+ */
112
+ declare function createLogger(config?: LoggerConfig): Logger;
113
+ /**
114
+ * Default logger instance.
115
+ */
116
+ declare const logger: Logger;
117
+
118
+ /**
119
+ * Safe JSON serialization with circular reference handling.
120
+ */
121
+ declare function safeStringify(value: unknown, indent?: number): string;
122
+ /**
123
+ * Format an Error object for structured logging.
124
+ */
125
+ interface SerializedError {
126
+ name: string;
127
+ message: string;
128
+ stack?: string;
129
+ cause?: SerializedError | unknown;
130
+ [key: string]: unknown;
131
+ }
132
+ declare function serializeError(err: unknown): SerializedError;
133
+
134
+ /**
135
+ * Color configuration per log level.
136
+ */
137
+ interface LevelStyle {
138
+ label: string;
139
+ color: string;
140
+ badge: string;
141
+ }
142
+ interface FormatOptions {
143
+ timestamp: boolean;
144
+ timestampFormat: 'iso' | 'short' | 'none';
145
+ namespace?: string | undefined;
146
+ }
147
+
148
+ export { type FormatOptions, type LevelStyle, type LogArgs, LogLevel, type LogLevelName, type LogLevelValue, type LogRecord, Logger, type LoggerConfig, type SerializedError, createLogger, detectColorSupport, getLevelName, getLevelValue, isColorsEnabled, isLogLevelName, logger, safeStringify, serializeError, setColorsEnabled };
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Log levels for pretty-logx.
3
+ * Lower numbers = more verbose.
4
+ */
5
+ declare const LogLevel: {
6
+ readonly trace: 10;
7
+ readonly debug: 20;
8
+ readonly info: 30;
9
+ readonly warn: 40;
10
+ readonly error: 50;
11
+ readonly fatal: 60;
12
+ readonly silent: number;
13
+ };
14
+ type LogLevelName = keyof typeof LogLevel;
15
+ type LogLevelValue = (typeof LogLevel)[LogLevelName];
16
+ declare function isLogLevelName(value: unknown): value is LogLevelName;
17
+ declare function getLevelValue(level: LogLevelName): number;
18
+ declare function getLevelName(value: number): LogLevelName | undefined;
19
+
20
+ /**
21
+ * Detect whether colors should be enabled.
22
+ * Checks: NO_COLOR env var, FORCE_COLOR env var, TTY availability.
23
+ */
24
+ declare function detectColorSupport(): boolean;
25
+ declare function isColorsEnabled(): boolean;
26
+ declare function setColorsEnabled(enabled: boolean): void;
27
+
28
+ /**
29
+ * Configuration for creating a logger.
30
+ */
31
+ interface LoggerConfig {
32
+ /** Minimum level to log. Defaults to 'info'. */
33
+ level?: LogLevelName;
34
+ /** Enable JSON mode (structured logging for production). */
35
+ json?: boolean;
36
+ /** Namespace/name prefix for this logger. */
37
+ namespace?: string | undefined;
38
+ /** Whether to include timestamps. Defaults to true. */
39
+ timestamp?: boolean;
40
+ /** Timestamp format. Defaults to 'short'. */
41
+ timestampFormat?: 'iso' | 'short' | 'none';
42
+ /** Enable/disable colors. Auto-detected by default. */
43
+ colors?: boolean;
44
+ /** Custom write function. Defaults to process.stdout/stderr. */
45
+ write?: (output: string, level: LogLevelName) => void;
46
+ }
47
+ /**
48
+ * Structured log record for JSON mode.
49
+ */
50
+ interface LogRecord {
51
+ level: LogLevelName;
52
+ levelValue: LogLevelValue;
53
+ time: string;
54
+ msg: string;
55
+ namespace?: string;
56
+ err?: unknown;
57
+ [key: string]: unknown;
58
+ }
59
+ /**
60
+ * Arguments to a log method: message + optional bindings.
61
+ */
62
+ type LogArgs = [message: string] | [message: string, ...meta: unknown[]] | [bindings: object, message: string];
63
+ /**
64
+ * Core Logger class.
65
+ */
66
+ declare class Logger {
67
+ private _level;
68
+ private _levelValue;
69
+ private _json;
70
+ private _namespace;
71
+ private _timestamp;
72
+ private _timestampFormat;
73
+ private _write;
74
+ private _bindings;
75
+ constructor(config?: LoggerConfig, parentBindings?: Record<string, unknown>);
76
+ get level(): LogLevelName;
77
+ set level(level: LogLevelName);
78
+ get levelValue(): number;
79
+ get namespace(): string | undefined;
80
+ get isJsonMode(): boolean;
81
+ get isTraceEnabled(): boolean;
82
+ get isDebugEnabled(): boolean;
83
+ get isInfoEnabled(): boolean;
84
+ get isWarnEnabled(): boolean;
85
+ get isErrorEnabled(): boolean;
86
+ get isFatalEnabled(): boolean;
87
+ private _log;
88
+ private _writeJson;
89
+ private _writePretty;
90
+ trace(...args: unknown[]): void;
91
+ debug(...args: unknown[]): void;
92
+ info(...args: unknown[]): void;
93
+ warn(...args: unknown[]): void;
94
+ error(...args: unknown[]): void;
95
+ fatal(...args: unknown[]): void;
96
+ /**
97
+ * Create a child logger with additional bindings and optional config overrides.
98
+ */
99
+ child(bindingsOrConfig: Record<string, unknown>, config?: Omit<LoggerConfig, 'namespace'>): Logger;
100
+ /**
101
+ * Create a namespaced child logger.
102
+ */
103
+ ns(namespace: string): Logger;
104
+ /**
105
+ * Configure this logger instance.
106
+ */
107
+ configure(config: Partial<LoggerConfig>): void;
108
+ }
109
+ /**
110
+ * Create a new logger instance.
111
+ */
112
+ declare function createLogger(config?: LoggerConfig): Logger;
113
+ /**
114
+ * Default logger instance.
115
+ */
116
+ declare const logger: Logger;
117
+
118
+ /**
119
+ * Safe JSON serialization with circular reference handling.
120
+ */
121
+ declare function safeStringify(value: unknown, indent?: number): string;
122
+ /**
123
+ * Format an Error object for structured logging.
124
+ */
125
+ interface SerializedError {
126
+ name: string;
127
+ message: string;
128
+ stack?: string;
129
+ cause?: SerializedError | unknown;
130
+ [key: string]: unknown;
131
+ }
132
+ declare function serializeError(err: unknown): SerializedError;
133
+
134
+ /**
135
+ * Color configuration per log level.
136
+ */
137
+ interface LevelStyle {
138
+ label: string;
139
+ color: string;
140
+ badge: string;
141
+ }
142
+ interface FormatOptions {
143
+ timestamp: boolean;
144
+ timestampFormat: 'iso' | 'short' | 'none';
145
+ namespace?: string | undefined;
146
+ }
147
+
148
+ export { type FormatOptions, type LevelStyle, type LogArgs, LogLevel, type LogLevelName, type LogLevelValue, type LogRecord, Logger, type LoggerConfig, type SerializedError, createLogger, detectColorSupport, getLevelName, getLevelValue, isColorsEnabled, isLogLevelName, logger, safeStringify, serializeError, setColorsEnabled };