@ricdotnet/logger 0.3.1 → 0.4.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/README.md ADDED
@@ -0,0 +1,284 @@
1
+ # @ricdotnet/logger
2
+
3
+ A lightweight, flexible logging library for TypeScript/JavaScript projects with support for custom formatters and transports.
4
+
5
+ ## Features
6
+
7
+ - 🎯 **Simple API** - Easy to use with sensible defaults
8
+ - 📦 **Modular** - Swap formatters and transports to suit your needs
9
+ - 🎨 **Multiple Formatters** - JSON and Pretty formatters included
10
+ - 📤 **Extensible Transports** - Console transport included, create your own
11
+ - 🌳 **Contextual Logging** - Add context that propagates through child loggers
12
+ - 📝 **Full TypeScript Support** - Built with TypeScript for type safety
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @ricdotnet/logger
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```typescript
23
+ import { Logger } from '@ricdotnet/logger';
24
+
25
+ const logger = new Logger();
26
+
27
+ logger.info('Application started');
28
+ logger.error('Something went wrong!');
29
+ ```
30
+
31
+ ## Usage
32
+
33
+ ### Basic Logging
34
+
35
+ The logger provides two main methods for logging:
36
+
37
+ ```typescript
38
+ import { Logger } from '@ricdotnet/logger';
39
+
40
+ const logger = new Logger();
41
+
42
+ // Log at info level
43
+ logger.info('User logged in');
44
+
45
+ // Log at error level
46
+ logger.error('Database connection failed');
47
+
48
+ // Generic log method with level specification
49
+ logger.log('warn', 'High memory usage detected');
50
+ ```
51
+
52
+ ### Log Levels
53
+
54
+ The logger supports the following log levels:
55
+
56
+ - `debug` - Detailed debug information
57
+ - `info` - General informational messages
58
+ - `warn` - Warning messages
59
+ - `error` - Error messages
60
+ - `fatal` - Fatal error messages (rarely recoverable)
61
+
62
+ ### Adding Context
63
+
64
+ You can pass an object as the second argument to add context to your logs:
65
+
66
+ ```typescript
67
+ logger.info('User action', {
68
+ userId: 123,
69
+ action: 'profile_update',
70
+ ip: '192.168.1.1',
71
+ });
72
+ ```
73
+
74
+ ### Configuration
75
+
76
+ The logger accepts an options object in its constructor:
77
+
78
+ ```typescript
79
+ import { Logger } from '@ricdotnet/logger';
80
+ import { PrettyFormatter } from '@ricdotnet/logger';
81
+
82
+ const logger = new Logger({
83
+ // Set the minimum log level
84
+ level: 'debug',
85
+
86
+ // Specify custom formatters (defaults to JsonFormatter)
87
+ formatter: new PrettyFormatter(),
88
+
89
+ // Add custom transports (defaults to Console transport)
90
+ transports: [
91
+ // Your custom transports here
92
+ ],
93
+
94
+ // Add default context that's included in all logs
95
+ context: {
96
+ service: 'api',
97
+ version: '1.0.0',
98
+ },
99
+ });
100
+ ```
101
+
102
+ ### Available Formatters
103
+
104
+ #### JsonFormatter (default)
105
+
106
+ Outputs logs as JSON, perfect for log aggregation services:
107
+
108
+ ```typescript
109
+ import { Logger } from '@ricdotnet/logger';
110
+
111
+ const logger = new Logger();
112
+ // Output: {"timestamp":"2024-11-01T10:30:45.123Z","level":"info","message":"User logged in"}
113
+ ```
114
+
115
+ #### PrettyFormatter
116
+
117
+ Human-readable format, great for development:
118
+
119
+ ```typescript
120
+ import { Logger, PrettyFormatter } from '@ricdotnet/logger';
121
+
122
+ const logger = new Logger({
123
+ formatter: new PrettyFormatter(),
124
+ });
125
+
126
+ logger.info('User logged in', { userId: 123 });
127
+ // Output: [11/1/2024, 10:30:45 AM] [INFO] User logged in {"userId":123}
128
+ ```
129
+
130
+ ### Using Transports
131
+
132
+ Transports determine where logs are written. The default console transport writes to `stdout` for info/debug/warn and `stderr` for error/fatal messages.
133
+
134
+ #### Console Transport (default)
135
+
136
+ ```typescript
137
+ import { Logger, ConsoleTransport } from '@ricdotnet/logger';
138
+
139
+ const logger = new Logger({
140
+ transports: [new ConsoleTransport()],
141
+ });
142
+ ```
143
+
144
+ #### Creating Custom Transports
145
+
146
+ Implement the `Transport` interface to create your own:
147
+
148
+ ```typescript
149
+ import { Logger, Transport, LogEntry } from '@ricdotnet/logger';
150
+
151
+ class FileTransport implements Transport {
152
+ constructor(private filepath: string) {}
153
+
154
+ write(entry: LogEntry, formatted: string): void {
155
+ // Write to file
156
+ fs.appendFileSync(this.filepath, formatted + '\n');
157
+ }
158
+
159
+ close(): void {
160
+ // Cleanup if needed
161
+ }
162
+ }
163
+
164
+ const logger = new Logger({
165
+ transports: [new ConsoleTransport(), new FileTransport('./logs/app.log')],
166
+ });
167
+ ```
168
+
169
+ ### Child Loggers
170
+
171
+ Create child loggers that inherit configuration and context from their parent:
172
+
173
+ ```typescript
174
+ const logger = new Logger({
175
+ context: { service: 'api' },
176
+ });
177
+
178
+ // Child logger inherits parent context
179
+ const requestLogger = logger.child({
180
+ requestId: 'abc-123',
181
+ userId: 456,
182
+ });
183
+
184
+ requestLogger.info('Request received');
185
+ // Logs include: { service: 'api', requestId: 'abc-123', userId: 456, ... }
186
+ ```
187
+
188
+ This is useful for associating logs with specific requests, operations, or components.
189
+
190
+ ## Complete Example
191
+
192
+ ```typescript
193
+ import { Logger, PrettyFormatter, type LogEntry } from '@ricdotnet/logger';
194
+
195
+ // Create a custom file transport
196
+ class FileTransport {
197
+ constructor(private filepath: string) {}
198
+
199
+ write(entry: LogEntry, formatted: string): void {
200
+ // Implementation here
201
+ }
202
+ }
203
+
204
+ // Initialize logger
205
+ const logger = new Logger({
206
+ level: 'debug',
207
+ formatter: new PrettyFormatter(),
208
+ transports: [new FileTransport('./logs/app.log')],
209
+ context: {
210
+ app: 'my-app',
211
+ environment: process.env.NODE_ENV,
212
+ },
213
+ });
214
+
215
+ // Use in your application
216
+ const userLogger = logger.child({ module: 'users' });
217
+ userLogger.info('Processing user registration', { email: 'user@example.com' });
218
+
219
+ try {
220
+ // Some operation
221
+ } catch (error) {
222
+ userLogger.error('Registration failed', { error: error.message });
223
+ }
224
+ ```
225
+
226
+ ## API Reference
227
+
228
+ ### Logger
229
+
230
+ #### Constructor
231
+
232
+ ```typescript
233
+ constructor(options?: {
234
+ level?: 'debug' | 'info' | 'warn' | 'error';
235
+ formatter?: Formatter;
236
+ transports?: Transport[];
237
+ context?: Record<string, unknown>;
238
+ })
239
+ ```
240
+
241
+ #### Methods
242
+
243
+ - `info(message: string, context?: Record<string, unknown>): void` - Log at info level
244
+ - `error(message: string, context?: Record<string, unknown>): void` - Log at error level
245
+ - `log(level: TLevel, message: string, context?: Record<string, unknown>): void` - Generic log method
246
+ - `child(context?: Record<string, unknown>): Logger` - Create a child logger with inherited context
247
+
248
+ ### Exports
249
+
250
+ ```typescript
251
+ import {
252
+ Logger, // Main logger class
253
+ PrettyFormatter, // Human-readable formatter
254
+ JsonFormatter, // JSON formatter
255
+ ConsoleTransport, // Console transport
256
+ // Types
257
+ type LogEntry,
258
+ type LogLevel,
259
+ type Formatter,
260
+ type Transport,
261
+ type TLevel,
262
+ } from '@ricdotnet/logger';
263
+ ```
264
+
265
+ ## TypeScript Support
266
+
267
+ All types are exported from the main package entry point:
268
+
269
+ ```typescript
270
+ import type {
271
+ LogEntry, // The log entry object
272
+ LogLevel, // Union type of all levels
273
+ Formatter, // Transport interface
274
+ Transport, // Transport interface
275
+ } from '@ricdotnet/logger';
276
+ ```
277
+
278
+ ## License
279
+
280
+ ISC
281
+
282
+ ## Author
283
+
284
+ ricdotnet - [ricr.dev](https://ricr.dev)
@@ -0,0 +1,4 @@
1
+ import type { Formatter, LogEntry } from '../types';
2
+ export declare class JsonFormatter implements Formatter {
3
+ format(entry: LogEntry): string;
4
+ }
@@ -0,0 +1,5 @@
1
+ export class JsonFormatter {
2
+ format(entry) {
3
+ return JSON.stringify(entry);
4
+ }
5
+ }
@@ -0,0 +1,4 @@
1
+ import type { Formatter, LogEntry } from '../types';
2
+ export declare class PrettyFormatter implements Formatter {
3
+ format(entry: LogEntry): string;
4
+ }
@@ -0,0 +1,7 @@
1
+ export class PrettyFormatter {
2
+ format(entry) {
3
+ const timestamp = new Date(entry.timestamp).toLocaleString();
4
+ const context = entry.context ? JSON.stringify(entry.context) : '';
5
+ return `[${timestamp}] [${entry.level.toUpperCase()}] ${entry.message} ${context}`;
6
+ }
7
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export { Logger } from './src/Logger';
1
+ export { Logger } from './logger';
2
+ export type { LogEntry, LogLevel, Formatter, Transport } from './types';
package/dist/index.js CHANGED
@@ -1,6 +1,2 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Logger = void 0;
4
- var Logger_1 = require("./src/Logger");
5
- Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return Logger_1.Logger; } });
6
- //# sourceMappingURL=index.js.map
1
+ // Main exports
2
+ export { Logger } from './logger';
@@ -0,0 +1,34 @@
1
+ import { Formatter, LogLevel, Transport } from './types';
2
+ type TOptions = {
3
+ name?: string;
4
+ level?: LogLevel;
5
+ transports?: Transport[];
6
+ context?: Record<string, unknown>;
7
+ formatter?: Formatter;
8
+ redact?: string[];
9
+ };
10
+ export declare class Logger {
11
+ private name;
12
+ private level;
13
+ private transports;
14
+ private context;
15
+ private formatter;
16
+ private redact;
17
+ constructor(options?: TOptions);
18
+ trace(message: string, context?: {}): void;
19
+ debug(message: string, context?: {}): void;
20
+ info(message: string, context?: {}): void;
21
+ warn(message: string, context?: {}): void;
22
+ error(message: string, context?: {}): void;
23
+ fatal(message: string, context?: {}): void;
24
+ log(level: LogLevel, message: string, context?: {}): void;
25
+ child(name: String, context?: Record<string, unknown>): Logger;
26
+ get _name(): string;
27
+ get _level(): LogLevel;
28
+ get _transports(): Transport[];
29
+ get _context(): Record<string, unknown>;
30
+ get _formatter(): Formatter;
31
+ get _redact(): string[];
32
+ private shouldLog;
33
+ }
34
+ export {};
package/dist/logger.js ADDED
@@ -0,0 +1,95 @@
1
+ import { JsonFormatter } from './formatters/json';
2
+ import { ConsoleTransport } from './transports/console';
3
+ export class Logger {
4
+ name;
5
+ level = 'info';
6
+ transports = [new ConsoleTransport()];
7
+ context;
8
+ formatter;
9
+ redact;
10
+ constructor(options = {}) {
11
+ this.name = options.name || 'default';
12
+ this.level = options.level || 'info';
13
+ this.transports = [...this.transports, ...(options.transports || [])];
14
+ this.context = options.context || {};
15
+ this.formatter = options.formatter || new JsonFormatter();
16
+ this.redact = options.redact || [];
17
+ }
18
+ trace(message, context = {}) {
19
+ this.log('trace', message, context);
20
+ }
21
+ debug(message, context = {}) {
22
+ this.log('debug', message, context);
23
+ }
24
+ info(message, context = {}) {
25
+ this.log('info', message, context);
26
+ }
27
+ warn(message, context = {}) {
28
+ this.log('warn', message, context);
29
+ }
30
+ error(message, context = {}) {
31
+ this.log('error', message, context);
32
+ }
33
+ fatal(message, context = {}) {
34
+ this.log('fatal', message, context);
35
+ }
36
+ log(level, message, context = {}) {
37
+ if (!this.shouldLog(level)) {
38
+ return;
39
+ }
40
+ const mergedContext = {
41
+ ...this.context,
42
+ ...context,
43
+ };
44
+ this.redact.forEach((key) => {
45
+ if (mergedContext[key]) {
46
+ mergedContext[key] = '******';
47
+ }
48
+ });
49
+ const entry = {
50
+ name: this.name,
51
+ timestamp: new Date().toISOString(),
52
+ level,
53
+ message,
54
+ ...mergedContext,
55
+ };
56
+ const output = this.formatter.format(entry);
57
+ for (const transport of this.transports) {
58
+ transport.write(entry, output);
59
+ }
60
+ }
61
+ child(name, context = {}) {
62
+ return new Logger({
63
+ name: `${this.name}.${name}`,
64
+ level: this.level,
65
+ transports: this.transports,
66
+ formatter: this.formatter,
67
+ redact: this.redact,
68
+ context: {
69
+ ...this.context,
70
+ ...context,
71
+ },
72
+ });
73
+ }
74
+ get _name() {
75
+ return this.name;
76
+ }
77
+ get _level() {
78
+ return this.level;
79
+ }
80
+ get _transports() {
81
+ return this.transports;
82
+ }
83
+ get _context() {
84
+ return this.context;
85
+ }
86
+ get _formatter() {
87
+ return this.formatter;
88
+ }
89
+ get _redact() {
90
+ return this.redact;
91
+ }
92
+ shouldLog(level) {
93
+ return this.level === 'debug' || level === this.level;
94
+ }
95
+ }
@@ -0,0 +1,5 @@
1
+ import { LogEntry, Transport } from '../types';
2
+ export declare class ConsoleTransport implements Transport {
3
+ write(entry: LogEntry, formatted: string): void;
4
+ close?(): void | Promise<void>;
5
+ }
@@ -0,0 +1,11 @@
1
+ export class ConsoleTransport {
2
+ write(entry, formatted) {
3
+ const output = entry.level === 'error' || entry.level === 'fatal'
4
+ ? process.stderr
5
+ : process.stdout;
6
+ output.write(`${formatted}\n`);
7
+ }
8
+ close() {
9
+ throw new Error('Method not implemented.');
10
+ }
11
+ }
@@ -0,0 +1,14 @@
1
+ export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal';
2
+ export interface LogEntry {
3
+ timestamp: string;
4
+ level: LogLevel;
5
+ message: string;
6
+ context?: Record<string, unknown>;
7
+ }
8
+ export interface Formatter {
9
+ format(entry: LogEntry): string;
10
+ }
11
+ export interface Transport {
12
+ write(entry: LogEntry, formatted: string): void | Promise<void>;
13
+ close?(): void | Promise<void>;
14
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,34 +1,45 @@
1
- {
2
- "name": "@ricdotnet/logger",
3
- "version": "0.3.1",
4
- "description": "A logger utility for my personal projects.",
5
- "main": "index.js",
6
- "scripts": {
7
- "start": "node dist/index.js",
8
- "dev": "ts-node index.ts",
9
- "build": "rm -rf ./dist && tsc",
10
- "test": "echo \"Error: no test specified\" && exit 1"
11
- },
12
- "keywords": [
13
- "logger",
14
- "logs",
15
- "console.log",
16
- "log",
17
- "logjs",
18
- "logts",
19
- "logger4ts",
20
- "logger4js"
21
- ],
22
- "author": "ricdotnet <me@rrocha.uk> https://ricr.dev",
23
- "repository": "https://github.com/ricdotnet/logger-utility",
24
- "license": "ISC",
25
- "devDependencies": {
26
- "@types/jest": "^27.4.1",
27
- "jest": "^27.5.1",
28
- "prettier": "3.1.1",
29
- "ts-jest": "^27.1.4",
30
- "ts-node": "^10.7.0",
31
- "typescript": "^4.6.3"
32
- },
33
- "dependencies": {}
34
- }
1
+ {
2
+ "name": "@ricdotnet/logger",
3
+ "version": "0.4.0",
4
+ "description": "A logger utility for my personal projects",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md"
16
+ ],
17
+ "scripts": {
18
+ "build": "tsc",
19
+ "clear": "rm -rf dist",
20
+ "prepublishOnly": "npm run clear && npm run build",
21
+ "test": "vitest"
22
+ },
23
+ "keywords": [
24
+ "logger",
25
+ "logs",
26
+ "console.log",
27
+ "log",
28
+ "logjs",
29
+ "logts",
30
+ "logger4ts",
31
+ "logger4js"
32
+ ],
33
+ "author": "ricdotnet <me@rrocha.uk> https://ricr.dev",
34
+ "repository": {
35
+ "url": "git+https://github.com/ricdotnet/logger.git"
36
+ },
37
+ "license": "ISC",
38
+ "devDependencies": {
39
+ "@types/node": "^26.6.6",
40
+ "@vitest/coverage-v8": "^5.0.5",
41
+ "prettier": "3.9.10",
42
+ "typescript": "7.0.2",
43
+ "vitest": "^5.0.5"
44
+ }
45
+ }
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"./","sources":["index.ts"],"names":[],"mappings":";;;AAAA,uCAAsC;AAA7B,gGAAA,MAAM,OAAA"}
@@ -1,25 +0,0 @@
1
- export declare enum Constants {
2
- RESET = "\u001B[0m",
3
- BRIGHT = "\u001B[1m",
4
- DIM = "\u001B[2m",
5
- UNDERSCORE = "\u001B[4m",
6
- BLINK = "\u001B[5m",
7
- REVERSE = "\u001B[7m",
8
- HIDDEN = "\u001B[8m",
9
- TEXT_BLACK = "\u001B[30m",
10
- TEXT_RED = "\u001B[31m",
11
- TEXT_GREEN = "\u001B[32m",
12
- TEXT_YELLOW = "\u001B[33m",
13
- TEXT_BLUE = "\u001B[34m",
14
- TEXT_MAGENTA = "\u001B[35m",
15
- TEXT_CYAN = "\u001B[36m",
16
- TEXT_WHITE = "\u001B[37m",
17
- BG_BLACK = "\u001B[40m",
18
- BG_RED = "\u001B[41m",
19
- BG_GREEN = "\u001B[42m",
20
- BG_YELLOW = "\u001B[43m",
21
- BG_BLUE = "\u001B[44m",
22
- BG_MAGENTA = "\u001B[45m",
23
- BG_CYAN = "\u001B[46m",
24
- BG_WHITE = "\u001B[47m"
25
- }
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Constants = void 0;
4
- var Constants;
5
- (function (Constants) {
6
- Constants["RESET"] = "\u001B[0m";
7
- Constants["BRIGHT"] = "\u001B[1m";
8
- Constants["DIM"] = "\u001B[2m";
9
- Constants["UNDERSCORE"] = "\u001B[4m";
10
- Constants["BLINK"] = "\u001B[5m";
11
- Constants["REVERSE"] = "\u001B[7m";
12
- Constants["HIDDEN"] = "\u001B[8m";
13
- Constants["TEXT_BLACK"] = "\u001B[30m";
14
- Constants["TEXT_RED"] = "\u001B[31m";
15
- Constants["TEXT_GREEN"] = "\u001B[32m";
16
- Constants["TEXT_YELLOW"] = "\u001B[33m";
17
- Constants["TEXT_BLUE"] = "\u001B[34m";
18
- Constants["TEXT_MAGENTA"] = "\u001B[35m";
19
- Constants["TEXT_CYAN"] = "\u001B[36m";
20
- Constants["TEXT_WHITE"] = "\u001B[37m";
21
- Constants["BG_BLACK"] = "\u001B[40m";
22
- Constants["BG_RED"] = "\u001B[41m";
23
- Constants["BG_GREEN"] = "\u001B[42m";
24
- Constants["BG_YELLOW"] = "\u001B[43m";
25
- Constants["BG_BLUE"] = "\u001B[44m";
26
- Constants["BG_MAGENTA"] = "\u001B[45m";
27
- Constants["BG_CYAN"] = "\u001B[46m";
28
- Constants["BG_WHITE"] = "\u001B[47m";
29
- })(Constants = exports.Constants || (exports.Constants = {}));
30
- //# sourceMappingURL=Constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Constants.js","sourceRoot":"./","sources":["src/Constants.ts"],"names":[],"mappings":";;;AAAA,IAAY,SA0BX;AA1BD,WAAY,SAAS;IACnB,gCAAwB,CAAA;IACxB,iCAAwB,CAAA;IACxB,8BAAwB,CAAA;IACxB,qCAAwB,CAAA;IACxB,gCAAwB,CAAA;IACxB,kCAAwB,CAAA;IACxB,iCAAwB,CAAA;IAExB,sCAAyB,CAAA;IACzB,oCAAyB,CAAA;IACzB,sCAAyB,CAAA;IACzB,uCAAyB,CAAA;IACzB,qCAAyB,CAAA;IACzB,wCAAyB,CAAA;IACzB,qCAAyB,CAAA;IACzB,sCAAyB,CAAA;IAEzB,oCAAyB,CAAA;IACzB,kCAAyB,CAAA;IACzB,oCAAyB,CAAA;IACzB,qCAAyB,CAAA;IACzB,mCAAyB,CAAA;IACzB,sCAAyB,CAAA;IACzB,mCAAyB,CAAA;IACzB,oCAAyB,CAAA;AAC3B,CAAC,EA1BW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QA0BpB"}
@@ -1,15 +0,0 @@
1
- import { ILogger } from './Types';
2
- export declare class Logger {
3
- private readonly logDir;
4
- private readonly logToConsole;
5
- private readonly logToFile;
6
- private readonly level;
7
- private static logger;
8
- private readonly logQueue;
9
- constructor(options?: ILogger);
10
- static get(): Logger;
11
- debug(message: string): Promise<void>;
12
- info(message: string): Promise<void>;
13
- warn(message: string): Promise<void>;
14
- error(message: string): Promise<void>;
15
- }
@@ -1,65 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Logger = void 0;
4
- const Constants_1 = require("./Constants");
5
- const Queue_1 = require("./Queue");
6
- class Logger {
7
- logDir;
8
- logToConsole;
9
- logToFile;
10
- level;
11
- static logger = null;
12
- logQueue;
13
- constructor(options) {
14
- console.log('Initiating a logger...');
15
- if (Logger.logger) {
16
- console.warn('The logger was already initiated.');
17
- return;
18
- }
19
- this.logToConsole = options?.logToConsole ?? true;
20
- this.logToFile = options?.logToFile ?? false;
21
- this.level = options?.level ?? 'info';
22
- Logger.logger = this;
23
- if (this.logToFile) {
24
- this.logQueue = new Queue_1.Queue(options);
25
- }
26
- console.log('Logger initiated.');
27
- }
28
- static get() {
29
- return Logger.logger;
30
- }
31
- async debug(message) {
32
- if (this.logToFile) {
33
- this.logQueue.add(message, 'debug');
34
- }
35
- if (this.logToConsole && this.level === 'debug') {
36
- console.debug(`${Constants_1.Constants.TEXT_CYAN}[DEBUG] (${new Date()}):${Constants_1.Constants.RESET} ${message}`);
37
- }
38
- }
39
- async info(message) {
40
- if (this.logToFile) {
41
- this.logQueue.add(message, 'info');
42
- }
43
- if (this.logToConsole) {
44
- console.log(`${Constants_1.Constants.TEXT_BLUE}[INFO] (${new Date()}):${Constants_1.Constants.RESET} ${message}`);
45
- }
46
- }
47
- async warn(message) {
48
- if (this.logToFile) {
49
- this.logQueue.add(message, 'warn');
50
- }
51
- if (this.logToConsole) {
52
- console.warn(`${Constants_1.Constants.TEXT_YELLOW}[WARN] (${new Date()}):${Constants_1.Constants.RESET} ${message}`);
53
- }
54
- }
55
- async error(message) {
56
- if (this.logToFile) {
57
- this.logQueue.add(message, 'error');
58
- }
59
- if (this.logToConsole) {
60
- console.error(`${Constants_1.Constants.TEXT_RED}[ERROR] (${new Date()}):${Constants_1.Constants.RESET} ${message}`);
61
- }
62
- }
63
- }
64
- exports.Logger = Logger;
65
- //# sourceMappingURL=Logger.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Logger.js","sourceRoot":"./","sources":["src/Logger.ts"],"names":[],"mappings":";;;AACA,2CAAwC;AAExC,mCAAgC;AAEhC,MAAa,MAAM;IACA,MAAM,CAAS;IACf,YAAY,CAAU;IACtB,SAAS,CAAU;IACnB,KAAK,CAAW;IACzB,MAAM,CAAC,MAAM,GAAW,IAAI,CAAC;IAEpB,QAAQ,CAAQ;IAEjC,YAAY,OAAiB;QAC3B,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;QACtC,IAAI,MAAM,CAAC,MAAM,EAAE;YACjB,OAAO,CAAC,IAAI,CAAC,mCAAmC,CAAC,CA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AAI,CAAC,OAAe;QACxB,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;SACpC;QACD,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,OAAO,CAAC,IAAI,CACV,GAAG,qBAAS,CAAC,WAAW,WAAW,IAAI,IAAI,EAAE,KAAK,qBAAS,CAAC,KAAK,IAAI,OAAO,EAAE,CAC/E,CAAC;SACH;IACH,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,OAAe;QACzB,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;SACrC;QACD,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,OAAO,CAAC,KAAK,CACX,GAAG,qBAAS,CAAC,QAAQ,YAAY,IAAI,IAAI,EAAE,KAAK,qBAAS,CAAC,KAAK,IAAI,OAAO,EAAE,CAC7E,CAAC;SACH;IACH,CAAC;;AAzEH,wBA0EC"}
@@ -1,11 +0,0 @@
1
- import { ILogger, LogLevel } from './Types';
2
- export declare class Queue {
3
- private logQueue;
4
- private isRunning;
5
- private readonly logDir;
6
- constructor(options: ILogger);
7
- private checkLogDir;
8
- add(message: string, level: LogLevel): void;
9
- runQueue(): Promise<void>;
10
- private writeToFile;
11
- }
package/dist/src/Queue.js DELETED
@@ -1,64 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Queue = void 0;
4
- const fs = require("fs/promises");
5
- const path = require("path");
6
- const Logger_1 = require("./Logger");
7
- class Queue {
8
- logQueue;
9
- isRunning;
10
- logDir;
11
- constructor(options) {
12
- this.logQueue = [];
13
- this.isRunning = false;
14
- this.logDir = options?.directory ?? 'Logs';
15
- this.checkLogDir();
16
- }
17
- async checkLogDir() {
18
- try {
19
- await fs.mkdir(this.logDir);
20
- await Logger_1.Logger.get().debug(`Logs folder generated. Logging to: ${this.logDir}`);
21
- }
22
- catch (error) {
23
- await Logger_1.Logger.get().debug(`Logs folder already exists. Logging to: ${this.logDir}`);
24
- }
25
- }
26
- add(message, level) {
27
- this.logQueue.push({ message, level });
28
- if (!this.isRunning) {
29
- this.isRunning = true;
30
- this.runQueue();
31
- }
32
- }
33
- async runQueue() {
34
- const { message, level } = this.logQueue.shift();
35
- await this.writeToFile(message, level);
36
- if (this.logQueue.length) {
37
- return this.runQueue();
38
- }
39
- this.isRunning = false;
40
- }
41
- async writeToFile(message, level) {
42
- const DAY = new Date().getDate();
43
- const MONTH = new Date().getMonth() + 1;
44
- const YEAR = new Date().getFullYear();
45
- const HOURS = new Date().getHours();
46
- const MINUTES = new Date().getMinutes();
47
- const FULL_DATE = [DAY, MONTH, YEAR].join('-');
48
- const FULL_TIME = [HOURS, MINUTES].join(':');
49
- let logFile;
50
- try {
51
- logFile = await fs.readFile(path.join(this.logDir, `${FULL_DATE}-${level}.log`));
52
- }
53
- catch (e) {
54
- const data = 'Log Time: ' + FULL_TIME + '\n' + message + '\n\n';
55
- await fs.writeFile(path.join(this.logDir, `${FULL_DATE}-${level}.log`), data);
56
- }
57
- if (logFile) {
58
- const data = logFile + 'Log Time: ' + FULL_TIME + '\n' + message + '\n\n';
59
- await fs.writeFile(path.join(this.logDir, `${FULL_DATE}-${level}.log`), data);
60
- }
61
- }
62
- }
63
- exports.Queue = Queue;
64
- //# sourceMappingURL=Queue.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Queue.js","sourceRoot":"./","sources":["src/Queue.ts"],"names":[],"mappings":";;;AAAA,kCAAkC;AAClC,6BAA6B;AAE7B,qCAAgC;AAEhC,MAAa,KAAK;IACR,QAAQ,CAAc;IACtB,SAAS,CAAU;IACV,MAAM,CAAS;IAEhC,YAAY,OAAgB;QAC1B,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;QACnB,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;QACvB,IAAI,CA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C;QAChD,MAAM,IAAI,GAAW,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QAC9C,MAAM,KAAK,GAAW,IAAI,IAAI,EAAE,CAAC,QAAQ,EAAE,CAAC;QAC5C,MAAM,OAAO,GAAW,IAAI,IAAI,EAAE,CAAC,UAAU,EAAE,CAAC;QAEhD,MAAM,SAAS,GAAW,CAAC,GAAG,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACvD,MAAM,SAAS,GAAW,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAErD,IAAI,OAAwB,CAAC;QAC7B,IAAI;YACF,OAAO,GAAG,MAAM,EAAE,CAAC,QAAQ,CACzB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,IAAI,KAAK,MAAM,CAAC,CACpD,CAAC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,IAAI,GAAG,YAAY,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,GAAG,MAAM,CAAC;YAChE,MAAM,EAAE,CAAC,SAAS,CAChB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,IAAI,KAAK,MAAM,CAAC,EACnD,IAAI,CACL,CAAC;SACH;QAED,IAAI,OAAO,EAAE;YACX,MAAM,IAAI,GAAG,OAAO,GAAG,YAAY,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,GAAG,MAAM,CAAC;YAC1E,MAAM,EAAE,CAAC,SAAS,CAChB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,SAAS,IAAI,KAAK,MAAM,CAAC,EACnD,IAAI,CACL,CAAC;SACH;IACH,CAAC;CACF;AAxED,sBAwEC"}
@@ -1,12 +0,0 @@
1
- export type Primitives = string | number | object;
2
- export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
3
- export type LogObject = {
4
- message: string;
5
- level: LogLevel;
6
- };
7
- export interface ILogger {
8
- directory?: string;
9
- logToConsole?: boolean;
10
- logToFile?: boolean;
11
- level?: LogLevel;
12
- }
package/dist/src/Types.js DELETED
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=Types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Types.js","sourceRoot":"./","sources":["src/Types.ts"],"names":[],"mappings":""}