logan-logger 1.1.3 → 1.1.7

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/README.md CHANGED
@@ -9,6 +9,7 @@ A universal TypeScript logging library that works consistently across all JavaSc
9
9
  ## Features
10
10
 
11
11
  - 🌐 **Universal Runtime Support** - Works in Node.js, Deno, Bun, browsers, and WebAssembly
12
+ - ⚛️ **Next.js Ready** - Full compatibility with App Router, Server Components, and API Routes
12
13
  - 🪶 **Zero Dependencies** - Core functionality with no required dependencies
13
14
  - ⚡ **Performance First** - Lazy evaluation, zero-allocation logging, minimal memory footprint
14
15
  - 🎯 **TypeScript Native** - Full type safety with comprehensive type definitions
@@ -58,6 +59,91 @@ const requestLogger = logger.child({
58
59
  requestLogger.info('Processing request', { endpoint: '/api/users' });
59
60
  ```
60
61
 
62
+ ### Next.js Integration
63
+
64
+ Logan Logger is fully compatible with Next.js 13+ App Router, including Server Components, Client Components, and API Routes.
65
+
66
+ #### Server Components
67
+ ```typescript
68
+ import { createLogger, LogLevel } from 'logan-logger';
69
+
70
+ const logger = createLogger({
71
+ level: process.env.NODE_ENV === 'development' ? LogLevel.DEBUG : LogLevel.INFO,
72
+ format: 'json'
73
+ });
74
+
75
+ export default async function ServerComponent() {
76
+ logger.info('Server component rendered');
77
+
78
+ // Server-side data fetching
79
+ const data = await fetchData();
80
+ logger.debug('Data fetched', { recordCount: data.length });
81
+
82
+ return <div>Server content</div>;
83
+ }
84
+ ```
85
+
86
+ #### Client Components
87
+ ```typescript
88
+ 'use client';
89
+
90
+ import { createLogger, LogLevel } from 'logan-logger';
91
+
92
+ const logger = createLogger({
93
+ level: LogLevel.INFO,
94
+ colorize: true
95
+ });
96
+
97
+ export default function ClientComponent() {
98
+ const handleClick = () => {
99
+ logger.info('User interaction', { action: 'button_click' });
100
+ };
101
+
102
+ return <button onClick={handleClick}>Click me</button>;
103
+ }
104
+ ```
105
+
106
+ #### API Routes
107
+ ```typescript
108
+ // app/api/users/route.ts
109
+ import { NextResponse } from 'next/server';
110
+ import { createLogger } from 'logan-logger';
111
+
112
+ const logger = createLogger({
113
+ format: 'json',
114
+ metadata: { service: 'api' }
115
+ });
116
+
117
+ export async function GET() {
118
+ const start = Date.now();
119
+ logger.info('API request started', { endpoint: '/api/users' });
120
+
121
+ try {
122
+ const users = await getUsers();
123
+ const duration = Date.now() - start;
124
+
125
+ logger.info('API request completed', {
126
+ statusCode: 200,
127
+ duration,
128
+ userCount: users.length
129
+ });
130
+
131
+ return NextResponse.json(users);
132
+ } catch (error) {
133
+ const duration = Date.now() - start;
134
+ logger.error('API request failed', {
135
+ statusCode: 500,
136
+ duration,
137
+ error: error instanceof Error ? error.message : 'Unknown error'
138
+ });
139
+
140
+ return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
141
+ }
142
+ }
143
+ ```
144
+
145
+ > **📋 See [Next.js Compatibility Guide](./docs/nextjs-compatibility.md) for complete setup instructions, advanced patterns, and troubleshooting.**
146
+
61
147
  ### Advanced Features
62
148
 
63
149
  #### Lazy Evaluation for Performance
@@ -150,6 +236,7 @@ logger.info('User processed', safeData);
150
236
 
151
237
  | Runtime | Import Path | Status | Implementation | Features |
152
238
  |---------|-------------|--------|----------------|----------|
239
+ | **Next.js 13+** | `logan-logger` | ✅ **Full** | **Auto-detection** | **Server/Client Components, API Routes, Edge Runtime** |
153
240
  | Node.js 20+ | `logan-logger/node` | ✅ Full | Winston + Console | File logging, transports, Morgan integration |
154
241
  | Bun | `logan-logger/bun` | ✅ Full | NodeLogger adapter | Same as Node.js |
155
242
  | Browser | `logan-logger/browser` | ✅ Full | Console API | CSS styling, performance marks, grouping |
package/dist/browser.d.ts CHANGED
@@ -1,331 +1,25 @@
1
- declare abstract class BaseLogger implements ILogger {
2
- protected level: LogLevel;
3
- protected config: Partial<LoggerConfig>;
4
- protected runtime: RuntimeName;
5
- protected childMetadata: Record<string, any>;
6
- protected constructor(config?: Partial<LoggerConfig>);
7
- debug(message: LogMessage, metadata?: any): void;
8
- info(message: LogMessage, metadata?: any): void;
9
- warn(message: LogMessage, metadata?: any): void;
10
- error(message: LogMessage, metadata?: any): void;
11
- log(level: LogLevel, message: LogMessage, metadata?: any): void;
12
- setLevel(level: LogLevel): void;
13
- getLevel(): LogLevel;
14
- child(metadata: Record<string, any>): ILogger;
15
- protected shouldLog(level: LogLevel): boolean;
16
- protected abstract writeLog(entry: LogEntry): void;
17
- protected abstract createChild(): BaseLogger;
18
- }
19
-
20
- export declare class BrowserLogger extends BaseLogger {
21
- constructor(config?: Partial<LoggerConfig>);
22
- protected writeLog(entry: LogEntry): void;
23
- protected createChild(): BaseLogger;
24
- private formatMessage;
25
- private getConsoleStyle;
26
- private shouldLogInProduction;
27
- protected shouldLog(level: LogLevel): boolean;
28
- }
29
-
30
- export declare class ConsoleGroupLogger extends BrowserLogger {
31
- private groupStack;
32
- group(label: string): void;
33
- groupCollapsed(label: string): void;
34
- groupEnd(): void;
35
- getCurrentGroupStack(): string[];
36
- getCurrentGroupPath(): string;
37
- time(label: string): void;
38
- timeEnd(label: string): void;
39
- trace(message: string, metadata?: any): void;
40
- count(label?: string): void;
41
- countReset(label?: string): void;
42
- table(data: any): void;
43
- }
44
-
45
- /**
46
- * Browser-specific logger factory function.
47
- * Creates a BrowserLogger instance without importing Node.js dependencies.
48
- */
49
- export declare function createLogger(config?: Partial<LoggerConfig>): ILogger;
50
-
51
- /**
52
- * Create a browser logger with configuration based on the current environment.
53
- * Automatically detects production/development/test environments and
54
- * sets appropriate log levels and formatting.
55
- */
56
- export declare function createLoggerForEnvironment(): ILogger;
57
-
58
- /**
59
- * Detects the current JavaScript runtime environment and its capabilities.
60
- * @returns Information about the detected runtime
61
- * @example
62
- * ```typescript
63
- * const runtime = detectRuntime();
64
- * console.log(`Running on: ${runtime.name} ${runtime.version}`);
65
- * ```
66
- */
67
- export declare function detectRuntime(): RuntimeInfo;
68
-
69
- /**
70
- * Filter out sensitive data from an object before logging.
71
- * @param obj - The object to filter
72
- * @param sensitiveKeys - Array of key names to redact (case-insensitive)
73
- * @returns A new object with sensitive values replaced with '[REDACTED]'
74
- * @example
75
- * ```typescript
76
- * const data = { username: 'john', password: 'secret123' };
77
- * const filtered = filterSensitiveData(data);
78
- * // Result: { username: 'john', password: '[REDACTED]' }
79
- * ```
80
- */
81
- export declare function filterSensitiveData(obj: any, sensitiveKeys?: string[]): any;
82
-
83
- /**
84
- * Format log level as a colored string for terminal output.
85
- * @param level - The log level to format
86
- * @param colorize - Whether to apply ANSI color codes
87
- * @returns Formatted level string with optional colors
88
- */
89
- export declare function formatLevel(level: LogLevel, colorize?: boolean): string;
90
-
91
- /**
92
- * Format a log entry for output in different formats.
93
- * @param entry - The log entry to format
94
- * @param format - Output format ('json' or 'text')
95
- * @returns Formatted log string
96
- * @example
97
- * ```typescript
98
- * const entry: LogEntry = {
99
- * timestamp: new Date(),
100
- * level: LogLevel.INFO,
101
- * message: 'User logged in',
102
- * metadata: { userId: 123 },
103
- * runtime: 'node'
104
- * };
105
- *
106
- * const textFormat = formatLogEntry(entry, 'text');
107
- * // Result: "[2024-01-01T12:00:00.000Z] INFO: User logged in {\"userId\":123}"
108
- *
109
- * const jsonFormat = formatLogEntry(entry, 'json');
110
- * // Result: {"timestamp":"2024-01-01T12:00:00.000Z","level":"info","message":"User logged in","metadata":{"userId":123},"runtime":"node"}
111
- * ```
112
- */
113
- export declare function formatLogEntry(entry: LogEntry, format?: 'json' | 'text'): string;
114
-
115
- /**
116
- * Main logger interface providing methods for logging at different levels.
117
- * This interface is implemented by all logger implementations across different runtimes.
118
- */
119
- export declare interface ILogger {
120
- /**
121
- * Log a debug message. Only shown when log level is DEBUG.
122
- * @param message - The message to log (string or lazy function)
123
- * @param metadata - Optional structured data to include
124
- */
125
- debug(message: LogMessage, metadata?: any): void;
126
- /**
127
- * Log an informational message.
128
- * @param message - The message to log (string or lazy function)
129
- * @param metadata - Optional structured data to include
130
- */
131
- info(message: LogMessage, metadata?: any): void;
132
- /**
133
- * Log a warning message.
134
- * @param message - The message to log (string or lazy function)
135
- * @param metadata - Optional structured data to include
136
- */
137
- warn(message: LogMessage, metadata?: any): void;
138
- /**
139
- * Log an error message.
140
- * @param message - The message to log (string or lazy function)
141
- * @param metadata - Optional structured data to include
142
- */
143
- error(message: LogMessage, metadata?: any): void;
144
- /**
145
- * Log a message at a specific level.
146
- * @param level - The log level
147
- * @param message - The message to log (string or lazy function)
148
- * @param metadata - Optional structured data to include
149
- */
150
- log(level: LogLevel, message: LogMessage, metadata?: any): void;
151
- /**
152
- * Set the minimum log level for this logger.
153
- * @param level - The minimum log level
154
- */
155
- setLevel(level: LogLevel): void;
156
- /**
157
- * Get the current minimum log level.
158
- * @returns The current log level
159
- */
160
- getLevel(): LogLevel;
161
- /**
162
- * Create a child logger with additional metadata.
163
- * @param metadata - Additional metadata to include in all child log messages
164
- * @returns A new logger instance with the additional metadata
165
- */
166
- child(metadata: Record<string, any>): ILogger;
167
- }
168
-
169
- /**
170
- * Check if the current runtime is a browser.
171
- * @returns True if running in a browser
172
- */
173
- export declare function isBrowser(): boolean;
174
-
175
- /**
176
- * Check if the current runtime is Bun.
177
- * @returns True if running in Bun
178
- */
179
- export declare function isBun(): boolean;
180
-
181
- /**
182
- * Check if the current runtime is Deno.
183
- * @returns True if running in Deno
184
- */
185
- export declare function isDeno(): boolean;
186
-
187
- /**
188
- * Check if the current runtime is Node.js.
189
- * @returns True if running in Node.js
190
- */
191
- export declare function isNode(): boolean;
192
-
193
- export declare const log: {
194
- debug: (message: string, meta?: any) => void;
195
- info: (message: string, meta?: any) => void;
196
- warn: (message: string, meta?: any) => void;
197
- error: (message: string, meta?: any) => void;
198
- };
199
-
200
- /**
201
- * Internal representation of a log entry.
202
- */
203
- declare interface LogEntry {
204
- /** When the log entry was created */
205
- timestamp: Date;
206
- /** Log level of this entry */
207
- level: LogLevel;
208
- /** The log message */
209
- message: string;
210
- /** Additional structured data */
211
- metadata?: Record<string, any>;
212
- /** Runtime that generated this log entry */
213
- runtime: RuntimeName;
214
- }
215
-
216
- export declare const logger: ILogger;
217
-
218
- /**
219
- * Configuration options for creating a logger instance.
220
- */
221
- export declare interface LoggerConfig {
222
- /** Minimum log level to output */
223
- level: LogLevel;
224
- /** Output format for log messages */
225
- format: 'json' | 'text' | 'custom';
226
- /** Whether to include timestamps in log output */
227
- timestamp: boolean;
228
- /** Whether to colorize log output (if supported) */
229
- colorize: boolean;
230
- /** Default metadata to include with all log messages */
231
- metadata: Record<string, any>;
232
- /** Transport configurations for log output */
233
- transports?: TransportConfig[];
234
- }
235
-
236
- /**
237
- * Log levels in ascending order of severity.
238
- * Used to filter which messages should be logged.
239
- */
240
- export declare enum LogLevel {
241
- /** Debug messages - most verbose */
242
- DEBUG = 0,
243
- /** Informational messages */
244
- INFO = 1,
245
- /** Warning messages */
246
- WARN = 2,
247
- /** Error messages */
248
- ERROR = 3,
249
- /** No messages - silent mode */
250
- SILENT = 4
251
- }
252
-
253
- /**
254
- * A log message can be a string or a function that returns a string.
255
- * Functions enable lazy evaluation for expensive log message generation.
256
- */
257
- declare type LogMessage = string | (() => string);
258
-
259
- export declare class PerformanceLogger extends BrowserLogger {
260
- mark(name: string): void;
261
- measure(name: string, startMark?: string, endMark?: string): void;
262
- clearMarks(name?: string): void;
263
- clearMeasures(name?: string): void;
264
- }
265
-
266
- /**
267
- * Capabilities that a runtime may or may not support.
268
- */
269
- declare interface RuntimeCapabilities {
270
- /** Whether the runtime supports file system operations */
271
- fileSystem: boolean;
272
- /** Whether the runtime supports colored console output */
273
- colorSupport: boolean;
274
- /** Whether the runtime provides process information */
275
- processInfo: boolean;
276
- /** Whether the runtime supports streams */
277
- streams: boolean;
278
- }
279
-
280
- /**
281
- * Information about the detected JavaScript runtime environment.
282
- */
283
- declare interface RuntimeInfo {
284
- /** The name of the runtime */
285
- name: RuntimeName;
286
- /** Version string of the runtime (if available) */
287
- version?: string;
288
- /** Capabilities supported by this runtime */
289
- capabilities: RuntimeCapabilities;
290
- }
291
-
292
- /**
293
- * Supported JavaScript runtime environments.
294
- */
295
- declare type RuntimeName = 'node' | 'deno' | 'bun' | 'browser' | 'webworker' | 'unknown';
296
-
297
- /**
298
- * Safely stringify an object to JSON, handling circular references,
299
- * Error objects, functions, and other non-serializable values.
300
- * @param obj - The object to stringify
301
- * @param space - Number of spaces for pretty-printing (optional)
302
- * @returns JSON string representation
303
- */
304
- export declare function safeStringify(obj: any, space?: number): string;
305
-
306
- /**
307
- * Serialize Error objects to plain objects for logging.
308
- * @param error - The error to serialize
309
- * @returns Serialized error object or original value if not an Error
310
- * @example
311
- * ```typescript
312
- * const error = new Error('Something went wrong');
313
- * const serialized = serializeError(error);
314
- * // Result: { name: 'Error', message: 'Something went wrong', stack: '...' }
315
- * ```
316
- */
317
- export declare function serializeError(error: any): any;
318
-
319
- /**
320
- * Configuration for a specific log transport (output destination).
321
- */
322
- declare interface TransportConfig {
323
- /** Type of transport */
324
- type: 'console' | 'file' | 'http' | 'custom';
325
- /** Minimum log level for this transport */
326
- level?: LogLevel;
327
- /** Transport-specific options */
328
- options: Record<string, any>;
329
- }
330
-
331
- export { }
1
+ import { LoggerConfig, ILogger } from './core/types';
2
+ export { BrowserLogger, ConsoleGroupLogger, PerformanceLogger } from './runtime/browser';
3
+ export type { ILogger, LoggerConfig } from './core/types';
4
+ export { LogLevel } from './core/types';
5
+ export * from './utils/runtime';
6
+ export * from './utils/serialization';
7
+ export * from './utils/formatting';
8
+ /**
9
+ * Browser-specific logger factory function.
10
+ * Creates a BrowserLogger instance without importing Node.js dependencies.
11
+ */
12
+ export declare function createLogger(config?: Partial<LoggerConfig>): ILogger;
13
+ /**
14
+ * Create a browser logger with configuration based on the current environment.
15
+ * Automatically detects production/development/test environments and
16
+ * sets appropriate log levels and formatting.
17
+ */
18
+ export declare function createLoggerForEnvironment(): ILogger;
19
+ export declare const logger: ILogger;
20
+ export declare const log: {
21
+ debug: (message: string, meta?: any) => void;
22
+ info: (message: string, meta?: any) => void;
23
+ warn: (message: string, meta?: any) => void;
24
+ error: (message: string, meta?: any) => void;
25
+ };