@geekmidas/logger 0.0.1

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 ADDED
@@ -0,0 +1,315 @@
1
+ # @geekmidas/logger
2
+
3
+ A simple and flexible structured logging library for Node.js and browsers with child logger support and context inheritance.
4
+
5
+ ## Features
6
+
7
+ - ✅ **Standard Interface**: Common logger interface with multiple log levels (debug, info, warn, error, fatal, trace)
8
+ - ✅ **Structured Logging**: Support for both structured (object + message) and simple (message only) logging
9
+ - ✅ **Child Loggers**: Create child loggers with inherited context
10
+ - ✅ **Automatic Timestamps**: Automatic timestamp injection on all log entries
11
+ - ✅ **Console-Based**: Built-in ConsoleLogger implementation using standard console methods
12
+ - ✅ **TypeScript**: Full TypeScript support with type-safe logging
13
+ - ✅ **Zero Dependencies**: No external dependencies
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pnpm add @geekmidas/logger
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ```typescript
24
+ import { ConsoleLogger } from '@geekmidas/logger';
25
+
26
+ // Create logger with initial context
27
+ const logger = new ConsoleLogger({ app: 'myApp', version: '1.0.0' });
28
+
29
+ // Structured logging
30
+ logger.info({ userId: 123, action: 'login' }, 'User logged in');
31
+ // Output: { app: 'myApp', version: '1.0.0', userId: 123, action: 'login', ts: 1234567890 } User logged in
32
+
33
+ // Simple logging
34
+ logger.info('Application started');
35
+ // Output: { app: 'myApp', version: '1.0.0', ts: 1234567890 } Application started
36
+
37
+ // Error logging
38
+ logger.error({ error, operation: 'fetchUser' }, 'Failed to fetch user');
39
+ ```
40
+
41
+ ## API Reference
42
+
43
+ ### Logger Interface
44
+
45
+ ```typescript
46
+ interface Logger {
47
+ debug: LogFn;
48
+ info: LogFn;
49
+ warn: LogFn;
50
+ error: LogFn;
51
+ fatal: LogFn;
52
+ trace: LogFn;
53
+ child: (obj: object) => Logger;
54
+ }
55
+ ```
56
+
57
+ ### Log Levels
58
+
59
+ - **trace** - Most detailed information
60
+ - **debug** - Verbose information for debugging
61
+ - **info** - General informational messages
62
+ - **warn** - Potentially harmful situations
63
+ - **error** - Error events that might still allow the application to continue
64
+ - **fatal** - Severe errors that will likely cause the application to abort
65
+
66
+ ### ConsoleLogger
67
+
68
+ ```typescript
69
+ class ConsoleLogger implements Logger {
70
+ constructor(data?: object)
71
+
72
+ debug: LogFn
73
+ info: LogFn
74
+ warn: LogFn
75
+ error: LogFn
76
+ fatal: LogFn
77
+ trace: LogFn
78
+ child(obj: object): Logger
79
+ }
80
+ ```
81
+
82
+ ## Usage Examples
83
+
84
+ ### Basic Logging
85
+
86
+ ```typescript
87
+ import { ConsoleLogger } from '@geekmidas/logger';
88
+
89
+ const logger = new ConsoleLogger({ service: 'api', environment: 'production' });
90
+
91
+ // Different log levels
92
+ logger.trace('Entering function');
93
+ logger.debug({ query: 'SELECT * FROM users' }, 'Executing query');
94
+ logger.info({ requestId: 'abc123' }, 'Request received');
95
+ logger.warn({ memoryUsage: '90%' }, 'High memory usage detected');
96
+ logger.error({ error: new Error('Connection failed') }, 'Database error');
97
+ logger.fatal({ exitCode: 1 }, 'Critical system failure');
98
+ ```
99
+
100
+ ### Structured Logging
101
+
102
+ ```typescript
103
+ const logger = new ConsoleLogger({ app: 'myApp' });
104
+
105
+ // Log with context object
106
+ logger.info(
107
+ {
108
+ userId: 123,
109
+ action: 'purchase',
110
+ productId: 'prod_456',
111
+ amount: 29.99
112
+ },
113
+ 'Purchase completed'
114
+ );
115
+
116
+ // Multiple additional arguments
117
+ logger.info(
118
+ { traceId: 'trace_123' },
119
+ 'Request processed in %dms',
120
+ 150
121
+ );
122
+ ```
123
+
124
+ ### Child Loggers
125
+
126
+ Child loggers inherit all context from their parent and add their own:
127
+
128
+ ```typescript
129
+ const parentLogger = new ConsoleLogger({
130
+ app: 'myApp',
131
+ environment: 'production'
132
+ });
133
+
134
+ // Create child logger for authentication module
135
+ const authLogger = parentLogger.child({ module: 'auth' });
136
+ authLogger.info({ userId: 123 }, 'User authenticated');
137
+ // Output: { app: 'myApp', environment: 'production', module: 'auth', userId: 123, ts: ... }
138
+
139
+ // Create child logger for database module
140
+ const dbLogger = parentLogger.child({ module: 'database' });
141
+ dbLogger.debug({ query: 'SELECT ...' }, 'Query executed');
142
+ // Output: { app: 'myApp', environment: 'production', module: 'database', query: 'SELECT ...', ts: ... }
143
+
144
+ // Child loggers can be nested
145
+ const userDbLogger = dbLogger.child({ table: 'users' });
146
+ userDbLogger.info({ rowsAffected: 1 }, 'Record inserted');
147
+ // Output: { app: 'myApp', environment: 'production', module: 'database', table: 'users', rowsAffected: 1, ts: ... }
148
+ ```
149
+
150
+ ### Request Context Pattern
151
+
152
+ ```typescript
153
+ import type { Logger } from '@geekmidas/logger';
154
+
155
+ function handleRequest(logger: Logger, requestId: string) {
156
+ // Create request-scoped logger
157
+ const requestLogger = logger.child({ requestId });
158
+
159
+ requestLogger.info('Processing request');
160
+
161
+ try {
162
+ processPayment(requestLogger);
163
+ requestLogger.info('Request completed');
164
+ } catch (error) {
165
+ requestLogger.error({ error }, 'Request failed');
166
+ }
167
+ }
168
+
169
+ function processPayment(logger: Logger) {
170
+ const paymentLogger = logger.child({ operation: 'payment' });
171
+ paymentLogger.debug({ amount: 100 }, 'Processing payment');
172
+ // All context is preserved: { requestId, operation, amount, ts }
173
+ }
174
+ ```
175
+
176
+ ### Integration with Services
177
+
178
+ ```typescript
179
+ class UserService {
180
+ private logger: Logger;
181
+
182
+ constructor(logger: Logger) {
183
+ this.logger = logger.child({ service: 'UserService' });
184
+ }
185
+
186
+ async createUser(data: UserData) {
187
+ this.logger.info({ email: data.email }, 'Creating user');
188
+
189
+ try {
190
+ const user = await this.db.insert(data);
191
+ this.logger.info({ userId: user.id }, 'User created successfully');
192
+ return user;
193
+ } catch (error) {
194
+ this.logger.error({ error, email: data.email }, 'Failed to create user');
195
+ throw error;
196
+ }
197
+ }
198
+
199
+ async deleteUser(userId: string) {
200
+ const logger = this.logger.child({ userId, operation: 'delete' });
201
+
202
+ logger.info('Deleting user');
203
+ await this.db.delete(userId);
204
+ logger.info('User deleted');
205
+ }
206
+ }
207
+ ```
208
+
209
+ ## Custom Logger Implementation
210
+
211
+ You can implement the `Logger` interface for custom logging backends:
212
+
213
+ ```typescript
214
+ import type { Logger, LogFn } from '@geekmidas/logger';
215
+
216
+ class CustomLogger implements Logger {
217
+ constructor(private context: object = {}) {}
218
+
219
+ private createLogFn(level: string): LogFn {
220
+ return (obj: any, msg?: string, ...args: any[]) => {
221
+ // Your custom logging implementation
222
+ const logEntry = {
223
+ level,
224
+ ...this.context,
225
+ ...obj,
226
+ timestamp: new Date().toISOString(),
227
+ message: msg
228
+ };
229
+
230
+ // Send to your logging service
231
+ yourLoggingService.send(logEntry);
232
+ };
233
+ }
234
+
235
+ debug: LogFn = this.createLogFn('debug');
236
+ info: LogFn = this.createLogFn('info');
237
+ warn: LogFn = this.createLogFn('warn');
238
+ error: LogFn = this.createLogFn('error');
239
+ fatal: LogFn = this.createLogFn('fatal');
240
+ trace: LogFn = this.createLogFn('trace');
241
+
242
+ child(obj: object): Logger {
243
+ return new CustomLogger({ ...this.context, ...obj });
244
+ }
245
+ }
246
+ ```
247
+
248
+ ## TypeScript Support
249
+
250
+ The library is written in TypeScript and provides full type definitions:
251
+
252
+ ```typescript
253
+ import type { Logger, LogFn } from '@geekmidas/logger';
254
+
255
+ // Use Logger type for dependency injection
256
+ function createService(logger: Logger) {
257
+ return {
258
+ doWork() {
259
+ logger.info('Working...');
260
+ }
261
+ };
262
+ }
263
+
264
+ // LogFn type for custom implementations
265
+ const customLog: LogFn = (obj, msg) => {
266
+ console.log(obj, msg);
267
+ };
268
+ ```
269
+
270
+ ## Best Practices
271
+
272
+ 1. **Create Base Logger Early**: Initialize your base logger at application startup with static context
273
+ ```typescript
274
+ const baseLogger = new ConsoleLogger({
275
+ app: 'myApp',
276
+ version: process.env.APP_VERSION,
277
+ environment: process.env.NODE_ENV
278
+ });
279
+ ```
280
+
281
+ 2. **Use Child Loggers**: Create child loggers for different modules/contexts rather than passing context repeatedly
282
+ ```typescript
283
+ const authLogger = baseLogger.child({ module: 'auth' });
284
+ const dbLogger = baseLogger.child({ module: 'db' });
285
+ ```
286
+
287
+ 3. **Structured Over String**: Prefer structured logging with context objects over string concatenation
288
+ ```typescript
289
+ // Good
290
+ logger.info({ userId, action: 'login', ip }, 'User logged in');
291
+
292
+ // Avoid
293
+ logger.info(`User ${userId} logged in from ${ip}`);
294
+ ```
295
+
296
+ 4. **Include Context**: Add relevant context to make logs searchable and debuggable
297
+ ```typescript
298
+ logger.error({
299
+ error: err,
300
+ userId,
301
+ requestId,
302
+ operation: 'fetchUser'
303
+ }, 'Operation failed');
304
+ ```
305
+
306
+ 5. **Dependency Injection**: Pass logger as dependency rather than importing globally
307
+ ```typescript
308
+ class MyService {
309
+ constructor(private logger: Logger) {}
310
+ }
311
+ ```
312
+
313
+ ## License
314
+
315
+ MIT
@@ -0,0 +1,94 @@
1
+
2
+ //#region src/console.ts
3
+ var ConsoleLogger = class ConsoleLogger {
4
+ /**
5
+ * Creates a new ConsoleLogger instance.
6
+ *
7
+ * @param data - Initial context data to include in all log messages
8
+ */
9
+ constructor(data = {}) {
10
+ this.data = data;
11
+ }
12
+ /**
13
+ * Creates a logging function that merges context data and adds timestamps.
14
+ *
15
+ * @param logMethod - The console method to use (e.g., console.log, console.error)
16
+ * @returns A LogFn that handles both structured and simple logging
17
+ * @private
18
+ */
19
+ createLogFn(logMethod) {
20
+ return (obj, msg, ...args) => {
21
+ const ts = Date.now();
22
+ const mergedData = {
23
+ ...this.data,
24
+ ...obj,
25
+ ts
26
+ };
27
+ if (msg) logMethod(mergedData, msg, ...args);
28
+ else logMethod(mergedData, ...args);
29
+ };
30
+ }
31
+ /** Debug level logging function */
32
+ debug = this.createLogFn(console.debug.bind(console));
33
+ /** Info level logging function */
34
+ info = this.createLogFn(console.info.bind(console));
35
+ /** Warning level logging function */
36
+ warn = this.createLogFn(console.warn.bind(console));
37
+ /** Error level logging function */
38
+ error = this.createLogFn(console.error.bind(console));
39
+ /** Fatal level logging function (uses console.error) */
40
+ fatal = this.createLogFn(console.error.bind(console));
41
+ /** Trace level logging function */
42
+ trace = this.createLogFn(console.trace.bind(console));
43
+ /**
44
+ * Creates a child logger with additional context data.
45
+ * The child logger inherits all context from the parent and adds its own.
46
+ *
47
+ * @param obj - Additional context data for the child logger
48
+ * @returns A new ConsoleLogger instance with merged context
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * const parentLogger = new ConsoleLogger({ app: 'myApp' });
53
+ * const childLogger = parentLogger.child({ module: 'database' });
54
+ * childLogger.info({ query: 'SELECT * FROM users' }, 'Query executed');
55
+ * // Context includes both { app: 'myApp' } and { module: 'database' }
56
+ * ```
57
+ */
58
+ child(obj) {
59
+ return new ConsoleLogger({
60
+ ...this.data,
61
+ ...obj
62
+ });
63
+ }
64
+ };
65
+ /**
66
+ * @example Basic usage
67
+ * ```typescript
68
+ * const logger = new ConsoleLogger({ app: 'myApp' });
69
+ * logger.info({ action: 'start' }, 'Application starting');
70
+ * // Logs: { app: 'myApp', action: 'start', ts: 1234567890 } Application starting
71
+ * ```
72
+ *
73
+ * @example Child logger usage
74
+ * ```typescript
75
+ * const childLogger = logger.child({ module: 'auth' });
76
+ * childLogger.debug({ userId: 123 }, 'User authenticated');
77
+ * // Logs: { app: 'myApp', module: 'auth', userId: 123, ts: 1234567891 } User authenticated
78
+ * ```
79
+ *
80
+ * @example Error logging with context
81
+ * ```typescript
82
+ * try {
83
+ * await someOperation();
84
+ * } catch (error) {
85
+ * logger.error({ error, operation: 'someOperation' }, 'Operation failed');
86
+ * }
87
+ * ```
88
+ */
89
+ const DEFAULT_LOGGER = new ConsoleLogger();
90
+
91
+ //#endregion
92
+ exports.ConsoleLogger = ConsoleLogger;
93
+ exports.DEFAULT_LOGGER = DEFAULT_LOGGER;
94
+ //# sourceMappingURL=console.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console.cjs","names":["data: object","logMethod: (...args: any[]) => void","obj: T","msg?: string","obj: object"],"sources":["../src/console.ts"],"sourcesContent":["import type { LogFn, Logger } from './types';\n\nexport class ConsoleLogger implements Logger {\n /**\n * Creates a new ConsoleLogger instance.\n *\n * @param data - Initial context data to include in all log messages\n */\n constructor(readonly data: object = {}) {}\n\n /**\n * Creates a logging function that merges context data and adds timestamps.\n *\n * @param logMethod - The console method to use (e.g., console.log, console.error)\n * @returns A LogFn that handles both structured and simple logging\n * @private\n */\n private createLogFn(logMethod: (...args: any[]) => void): LogFn {\n return <T extends object>(obj: T, msg?: string, ...args: any[]): void => {\n // Merge the logger's context data with the provided object\n const ts = Date.now();\n const mergedData = { ...this.data, ...obj, ts };\n\n if (msg) {\n logMethod(mergedData, msg, ...args);\n } else {\n logMethod(mergedData, ...args);\n }\n };\n }\n\n /** Debug level logging function */\n debug: LogFn = this.createLogFn(console.debug.bind(console));\n /** Info level logging function */\n info: LogFn = this.createLogFn(console.info.bind(console));\n /** Warning level logging function */\n warn: LogFn = this.createLogFn(console.warn.bind(console));\n /** Error level logging function */\n error: LogFn = this.createLogFn(console.error.bind(console));\n /** Fatal level logging function (uses console.error) */\n fatal: LogFn = this.createLogFn(console.error.bind(console));\n /** Trace level logging function */\n trace: LogFn = this.createLogFn(console.trace.bind(console));\n\n /**\n * Creates a child logger with additional context data.\n * The child logger inherits all context from the parent and adds its own.\n *\n * @param obj - Additional context data for the child logger\n * @returns A new ConsoleLogger instance with merged context\n *\n * @example\n * ```typescript\n * const parentLogger = new ConsoleLogger({ app: 'myApp' });\n * const childLogger = parentLogger.child({ module: 'database' });\n * childLogger.info({ query: 'SELECT * FROM users' }, 'Query executed');\n * // Context includes both { app: 'myApp' } and { module: 'database' }\n * ```\n */\n child(obj: object): Logger {\n return new ConsoleLogger({\n ...this.data,\n ...obj,\n });\n }\n}\n\n/**\n * @example Basic usage\n * ```typescript\n * const logger = new ConsoleLogger({ app: 'myApp' });\n * logger.info({ action: 'start' }, 'Application starting');\n * // Logs: { app: 'myApp', action: 'start', ts: 1234567890 } Application starting\n * ```\n *\n * @example Child logger usage\n * ```typescript\n * const childLogger = logger.child({ module: 'auth' });\n * childLogger.debug({ userId: 123 }, 'User authenticated');\n * // Logs: { app: 'myApp', module: 'auth', userId: 123, ts: 1234567891 } User authenticated\n * ```\n *\n * @example Error logging with context\n * ```typescript\n * try {\n * await someOperation();\n * } catch (error) {\n * logger.error({ error, operation: 'someOperation' }, 'Operation failed');\n * }\n * ```\n */\n\nexport const DEFAULT_LOGGER = new ConsoleLogger() as any;\n"],"mappings":";;AAEA,IAAa,gBAAb,MAAa,cAAgC;;;;;;CAM3C,YAAqBA,OAAe,CAAE,GAAE;EAAnB;CAAqB;;;;;;;;CAS1C,AAAQ,YAAYC,WAA4C;AAC9D,SAAO,CAAmBC,KAAQC,KAAc,GAAG,SAAsB;GAEvE,MAAM,KAAK,KAAK,KAAK;GACrB,MAAM,aAAa;IAAE,GAAG,KAAK;IAAM,GAAG;IAAK;GAAI;AAE/C,OAAI,IACF,WAAU,YAAY,KAAK,GAAG,KAAK;OAEnC,WAAU,YAAY,GAAG,KAAK;EAEjC;CACF;;CAGD,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;CAE5D,OAAc,KAAK,YAAY,QAAQ,KAAK,KAAK,QAAQ,CAAC;;CAE1D,OAAc,KAAK,YAAY,QAAQ,KAAK,KAAK,QAAQ,CAAC;;CAE1D,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;CAE5D,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;CAE5D,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;;;;;;;;;;;;;;;CAiB5D,MAAMC,KAAqB;AACzB,SAAO,IAAI,cAAc;GACvB,GAAG,KAAK;GACR,GAAG;EACJ;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA2BD,MAAa,iBAAiB,IAAI"}
@@ -0,0 +1,76 @@
1
+ import { LogFn, Logger } from "./types-DXdmn7h5.cjs";
2
+
3
+ //#region src/console.d.ts
4
+ declare class ConsoleLogger implements Logger {
5
+ readonly data: object;
6
+ /**
7
+ * Creates a new ConsoleLogger instance.
8
+ *
9
+ * @param data - Initial context data to include in all log messages
10
+ */
11
+ constructor(data?: object);
12
+ /**
13
+ * Creates a logging function that merges context data and adds timestamps.
14
+ *
15
+ * @param logMethod - The console method to use (e.g., console.log, console.error)
16
+ * @returns A LogFn that handles both structured and simple logging
17
+ * @private
18
+ */
19
+ private createLogFn;
20
+ /** Debug level logging function */
21
+ debug: LogFn;
22
+ /** Info level logging function */
23
+ info: LogFn;
24
+ /** Warning level logging function */
25
+ warn: LogFn;
26
+ /** Error level logging function */
27
+ error: LogFn;
28
+ /** Fatal level logging function (uses console.error) */
29
+ fatal: LogFn;
30
+ /** Trace level logging function */
31
+ trace: LogFn;
32
+ /**
33
+ * Creates a child logger with additional context data.
34
+ * The child logger inherits all context from the parent and adds its own.
35
+ *
36
+ * @param obj - Additional context data for the child logger
37
+ * @returns A new ConsoleLogger instance with merged context
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const parentLogger = new ConsoleLogger({ app: 'myApp' });
42
+ * const childLogger = parentLogger.child({ module: 'database' });
43
+ * childLogger.info({ query: 'SELECT * FROM users' }, 'Query executed');
44
+ * // Context includes both { app: 'myApp' } and { module: 'database' }
45
+ * ```
46
+ */
47
+ child(obj: object): Logger;
48
+ }
49
+ /**
50
+ * @example Basic usage
51
+ * ```typescript
52
+ * const logger = new ConsoleLogger({ app: 'myApp' });
53
+ * logger.info({ action: 'start' }, 'Application starting');
54
+ * // Logs: { app: 'myApp', action: 'start', ts: 1234567890 } Application starting
55
+ * ```
56
+ *
57
+ * @example Child logger usage
58
+ * ```typescript
59
+ * const childLogger = logger.child({ module: 'auth' });
60
+ * childLogger.debug({ userId: 123 }, 'User authenticated');
61
+ * // Logs: { app: 'myApp', module: 'auth', userId: 123, ts: 1234567891 } User authenticated
62
+ * ```
63
+ *
64
+ * @example Error logging with context
65
+ * ```typescript
66
+ * try {
67
+ * await someOperation();
68
+ * } catch (error) {
69
+ * logger.error({ error, operation: 'someOperation' }, 'Operation failed');
70
+ * }
71
+ * ```
72
+ */
73
+ declare const DEFAULT_LOGGER: any;
74
+ //#endregion
75
+ export { ConsoleLogger, DEFAULT_LOGGER };
76
+ //# sourceMappingURL=console.d.cts.map
@@ -0,0 +1,76 @@
1
+ import { LogFn, Logger } from "./types-C1RfRbo6.mjs";
2
+
3
+ //#region src/console.d.ts
4
+ declare class ConsoleLogger implements Logger {
5
+ readonly data: object;
6
+ /**
7
+ * Creates a new ConsoleLogger instance.
8
+ *
9
+ * @param data - Initial context data to include in all log messages
10
+ */
11
+ constructor(data?: object);
12
+ /**
13
+ * Creates a logging function that merges context data and adds timestamps.
14
+ *
15
+ * @param logMethod - The console method to use (e.g., console.log, console.error)
16
+ * @returns A LogFn that handles both structured and simple logging
17
+ * @private
18
+ */
19
+ private createLogFn;
20
+ /** Debug level logging function */
21
+ debug: LogFn;
22
+ /** Info level logging function */
23
+ info: LogFn;
24
+ /** Warning level logging function */
25
+ warn: LogFn;
26
+ /** Error level logging function */
27
+ error: LogFn;
28
+ /** Fatal level logging function (uses console.error) */
29
+ fatal: LogFn;
30
+ /** Trace level logging function */
31
+ trace: LogFn;
32
+ /**
33
+ * Creates a child logger with additional context data.
34
+ * The child logger inherits all context from the parent and adds its own.
35
+ *
36
+ * @param obj - Additional context data for the child logger
37
+ * @returns A new ConsoleLogger instance with merged context
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const parentLogger = new ConsoleLogger({ app: 'myApp' });
42
+ * const childLogger = parentLogger.child({ module: 'database' });
43
+ * childLogger.info({ query: 'SELECT * FROM users' }, 'Query executed');
44
+ * // Context includes both { app: 'myApp' } and { module: 'database' }
45
+ * ```
46
+ */
47
+ child(obj: object): Logger;
48
+ }
49
+ /**
50
+ * @example Basic usage
51
+ * ```typescript
52
+ * const logger = new ConsoleLogger({ app: 'myApp' });
53
+ * logger.info({ action: 'start' }, 'Application starting');
54
+ * // Logs: { app: 'myApp', action: 'start', ts: 1234567890 } Application starting
55
+ * ```
56
+ *
57
+ * @example Child logger usage
58
+ * ```typescript
59
+ * const childLogger = logger.child({ module: 'auth' });
60
+ * childLogger.debug({ userId: 123 }, 'User authenticated');
61
+ * // Logs: { app: 'myApp', module: 'auth', userId: 123, ts: 1234567891 } User authenticated
62
+ * ```
63
+ *
64
+ * @example Error logging with context
65
+ * ```typescript
66
+ * try {
67
+ * await someOperation();
68
+ * } catch (error) {
69
+ * logger.error({ error, operation: 'someOperation' }, 'Operation failed');
70
+ * }
71
+ * ```
72
+ */
73
+ declare const DEFAULT_LOGGER: any;
74
+ //#endregion
75
+ export { ConsoleLogger, DEFAULT_LOGGER };
76
+ //# sourceMappingURL=console.d.mts.map
@@ -0,0 +1,92 @@
1
+ //#region src/console.ts
2
+ var ConsoleLogger = class ConsoleLogger {
3
+ /**
4
+ * Creates a new ConsoleLogger instance.
5
+ *
6
+ * @param data - Initial context data to include in all log messages
7
+ */
8
+ constructor(data = {}) {
9
+ this.data = data;
10
+ }
11
+ /**
12
+ * Creates a logging function that merges context data and adds timestamps.
13
+ *
14
+ * @param logMethod - The console method to use (e.g., console.log, console.error)
15
+ * @returns A LogFn that handles both structured and simple logging
16
+ * @private
17
+ */
18
+ createLogFn(logMethod) {
19
+ return (obj, msg, ...args) => {
20
+ const ts = Date.now();
21
+ const mergedData = {
22
+ ...this.data,
23
+ ...obj,
24
+ ts
25
+ };
26
+ if (msg) logMethod(mergedData, msg, ...args);
27
+ else logMethod(mergedData, ...args);
28
+ };
29
+ }
30
+ /** Debug level logging function */
31
+ debug = this.createLogFn(console.debug.bind(console));
32
+ /** Info level logging function */
33
+ info = this.createLogFn(console.info.bind(console));
34
+ /** Warning level logging function */
35
+ warn = this.createLogFn(console.warn.bind(console));
36
+ /** Error level logging function */
37
+ error = this.createLogFn(console.error.bind(console));
38
+ /** Fatal level logging function (uses console.error) */
39
+ fatal = this.createLogFn(console.error.bind(console));
40
+ /** Trace level logging function */
41
+ trace = this.createLogFn(console.trace.bind(console));
42
+ /**
43
+ * Creates a child logger with additional context data.
44
+ * The child logger inherits all context from the parent and adds its own.
45
+ *
46
+ * @param obj - Additional context data for the child logger
47
+ * @returns A new ConsoleLogger instance with merged context
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * const parentLogger = new ConsoleLogger({ app: 'myApp' });
52
+ * const childLogger = parentLogger.child({ module: 'database' });
53
+ * childLogger.info({ query: 'SELECT * FROM users' }, 'Query executed');
54
+ * // Context includes both { app: 'myApp' } and { module: 'database' }
55
+ * ```
56
+ */
57
+ child(obj) {
58
+ return new ConsoleLogger({
59
+ ...this.data,
60
+ ...obj
61
+ });
62
+ }
63
+ };
64
+ /**
65
+ * @example Basic usage
66
+ * ```typescript
67
+ * const logger = new ConsoleLogger({ app: 'myApp' });
68
+ * logger.info({ action: 'start' }, 'Application starting');
69
+ * // Logs: { app: 'myApp', action: 'start', ts: 1234567890 } Application starting
70
+ * ```
71
+ *
72
+ * @example Child logger usage
73
+ * ```typescript
74
+ * const childLogger = logger.child({ module: 'auth' });
75
+ * childLogger.debug({ userId: 123 }, 'User authenticated');
76
+ * // Logs: { app: 'myApp', module: 'auth', userId: 123, ts: 1234567891 } User authenticated
77
+ * ```
78
+ *
79
+ * @example Error logging with context
80
+ * ```typescript
81
+ * try {
82
+ * await someOperation();
83
+ * } catch (error) {
84
+ * logger.error({ error, operation: 'someOperation' }, 'Operation failed');
85
+ * }
86
+ * ```
87
+ */
88
+ const DEFAULT_LOGGER = new ConsoleLogger();
89
+
90
+ //#endregion
91
+ export { ConsoleLogger, DEFAULT_LOGGER };
92
+ //# sourceMappingURL=console.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console.mjs","names":["data: object","logMethod: (...args: any[]) => void","obj: T","msg?: string","obj: object"],"sources":["../src/console.ts"],"sourcesContent":["import type { LogFn, Logger } from './types';\n\nexport class ConsoleLogger implements Logger {\n /**\n * Creates a new ConsoleLogger instance.\n *\n * @param data - Initial context data to include in all log messages\n */\n constructor(readonly data: object = {}) {}\n\n /**\n * Creates a logging function that merges context data and adds timestamps.\n *\n * @param logMethod - The console method to use (e.g., console.log, console.error)\n * @returns A LogFn that handles both structured and simple logging\n * @private\n */\n private createLogFn(logMethod: (...args: any[]) => void): LogFn {\n return <T extends object>(obj: T, msg?: string, ...args: any[]): void => {\n // Merge the logger's context data with the provided object\n const ts = Date.now();\n const mergedData = { ...this.data, ...obj, ts };\n\n if (msg) {\n logMethod(mergedData, msg, ...args);\n } else {\n logMethod(mergedData, ...args);\n }\n };\n }\n\n /** Debug level logging function */\n debug: LogFn = this.createLogFn(console.debug.bind(console));\n /** Info level logging function */\n info: LogFn = this.createLogFn(console.info.bind(console));\n /** Warning level logging function */\n warn: LogFn = this.createLogFn(console.warn.bind(console));\n /** Error level logging function */\n error: LogFn = this.createLogFn(console.error.bind(console));\n /** Fatal level logging function (uses console.error) */\n fatal: LogFn = this.createLogFn(console.error.bind(console));\n /** Trace level logging function */\n trace: LogFn = this.createLogFn(console.trace.bind(console));\n\n /**\n * Creates a child logger with additional context data.\n * The child logger inherits all context from the parent and adds its own.\n *\n * @param obj - Additional context data for the child logger\n * @returns A new ConsoleLogger instance with merged context\n *\n * @example\n * ```typescript\n * const parentLogger = new ConsoleLogger({ app: 'myApp' });\n * const childLogger = parentLogger.child({ module: 'database' });\n * childLogger.info({ query: 'SELECT * FROM users' }, 'Query executed');\n * // Context includes both { app: 'myApp' } and { module: 'database' }\n * ```\n */\n child(obj: object): Logger {\n return new ConsoleLogger({\n ...this.data,\n ...obj,\n });\n }\n}\n\n/**\n * @example Basic usage\n * ```typescript\n * const logger = new ConsoleLogger({ app: 'myApp' });\n * logger.info({ action: 'start' }, 'Application starting');\n * // Logs: { app: 'myApp', action: 'start', ts: 1234567890 } Application starting\n * ```\n *\n * @example Child logger usage\n * ```typescript\n * const childLogger = logger.child({ module: 'auth' });\n * childLogger.debug({ userId: 123 }, 'User authenticated');\n * // Logs: { app: 'myApp', module: 'auth', userId: 123, ts: 1234567891 } User authenticated\n * ```\n *\n * @example Error logging with context\n * ```typescript\n * try {\n * await someOperation();\n * } catch (error) {\n * logger.error({ error, operation: 'someOperation' }, 'Operation failed');\n * }\n * ```\n */\n\nexport const DEFAULT_LOGGER = new ConsoleLogger() as any;\n"],"mappings":";AAEA,IAAa,gBAAb,MAAa,cAAgC;;;;;;CAM3C,YAAqBA,OAAe,CAAE,GAAE;EAAnB;CAAqB;;;;;;;;CAS1C,AAAQ,YAAYC,WAA4C;AAC9D,SAAO,CAAmBC,KAAQC,KAAc,GAAG,SAAsB;GAEvE,MAAM,KAAK,KAAK,KAAK;GACrB,MAAM,aAAa;IAAE,GAAG,KAAK;IAAM,GAAG;IAAK;GAAI;AAE/C,OAAI,IACF,WAAU,YAAY,KAAK,GAAG,KAAK;OAEnC,WAAU,YAAY,GAAG,KAAK;EAEjC;CACF;;CAGD,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;CAE5D,OAAc,KAAK,YAAY,QAAQ,KAAK,KAAK,QAAQ,CAAC;;CAE1D,OAAc,KAAK,YAAY,QAAQ,KAAK,KAAK,QAAQ,CAAC;;CAE1D,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;CAE5D,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;CAE5D,QAAe,KAAK,YAAY,QAAQ,MAAM,KAAK,QAAQ,CAAC;;;;;;;;;;;;;;;;CAiB5D,MAAMC,KAAqB;AACzB,SAAO,IAAI,cAAc;GACvB,GAAG,KAAK;GACR,GAAG;EACJ;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA2BD,MAAa,iBAAiB,IAAI"}
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ const require_types = require('./types-ag_0Cvbg.cjs');
2
+
3
+ exports.LogLevel = require_types.LogLevel;
@@ -0,0 +1,2 @@
1
+ import { CreateLoggerOptions, LogFn, LogLevel, Logger } from "./types-DXdmn7h5.cjs";
2
+ export { CreateLoggerOptions, LogFn, LogLevel, Logger };
@@ -0,0 +1,2 @@
1
+ import { CreateLoggerOptions, LogFn, LogLevel, Logger } from "./types-C1RfRbo6.mjs";
2
+ export { CreateLoggerOptions, LogFn, LogLevel, Logger };
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import { LogLevel } from "./types-yQ6XOihF.mjs";
2
+
3
+ export { LogLevel };