@nu-art/logger 0.401.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.
@@ -0,0 +1,89 @@
1
+ /*
2
+ * @nu-art/logger - Flexible logging infrastructure with multiple output targets
3
+ * Copyright (C) 2024 Adam van der Kruk aka TacB0sS
4
+ * Licensed under the Apache License, Version 2.0
5
+ */
6
+ import * as fs from 'fs';
7
+ import { LogClient_BaseRotate } from './LogClient_BaseRotate.js';
8
+ /**
9
+ * Log client that writes logs to rotating files on disk.
10
+ *
11
+ * Creates log files in the format `{name}-{index}.txt` where index 0 is the current log.
12
+ * When the current log exceeds maxSize, it rotates: log-0.txt → log-1.txt, log-1.txt → log-2.txt, etc.
13
+ * The oldest log (log-{maxEntries-1}.txt) is deleted during rotation.
14
+ *
15
+ * The log folder is created automatically if it doesn't exist. If a log file already
16
+ * exists, its size is used to initialize the bufferSize counter.
17
+ */
18
+ export class LogClient_File extends LogClient_BaseRotate {
19
+ /** Directory path where log files are stored */
20
+ pathToFolder;
21
+ /** WriteStream for the current log file */
22
+ buffer;
23
+ /**
24
+ * Creates a new file-based log client.
25
+ *
26
+ * @param name - Log file name prefix (e.g., "app" creates "app-0.txt", "app-1.txt", etc.)
27
+ * @param pathToFolder - Directory path for log files (created if it doesn't exist)
28
+ * @param maxEntries - Maximum number of rotated log files to keep (default: 10)
29
+ * @param maxSize - Maximum file size in bytes before rotation (default: 1MB)
30
+ */
31
+ constructor(name, pathToFolder, maxEntries = 10, maxSize = 1024 * 1024) {
32
+ super(name, maxEntries, maxSize);
33
+ this.pathToFolder = pathToFolder;
34
+ if (!fs.existsSync(pathToFolder))
35
+ fs.mkdirSync(pathToFolder, { recursive: true });
36
+ const defaultLogfile = this.getFileName();
37
+ if (fs.existsSync(defaultLogfile))
38
+ this.bufferSize = fs.statSync(`${defaultLogfile}`).size;
39
+ this.prepare();
40
+ }
41
+ /**
42
+ * Gets the filename for a log file at the given index.
43
+ *
44
+ * @param index - Log file index (0 = current, 1+ = rotated)
45
+ * @returns Full path to the log file
46
+ */
47
+ getFileName(index = 0) {
48
+ return `${this.pathToFolder}/${this.name}-${index}.txt`;
49
+ }
50
+ /**
51
+ * Writes a log message to the current log file.
52
+ *
53
+ * @param log - Formatted log string (includes newline)
54
+ */
55
+ printLogMessage(log) {
56
+ this.buffer.write(log);
57
+ }
58
+ /**
59
+ * Rotates a log file by renaming it to the next index.
60
+ *
61
+ * @param fromIndex - Source index
62
+ * @param toIndex - Destination index
63
+ */
64
+ rotateBuffer(fromIndex, toIndex) {
65
+ if (fs.existsSync(this.getFileName(fromIndex))) {
66
+ console.log(`rotating ${fromIndex} => ${toIndex}`);
67
+ fs.renameSync(this.getFileName(fromIndex), this.getFileName(toIndex));
68
+ }
69
+ }
70
+ /**
71
+ * Cleans up the oldest log file and closes the current write stream.
72
+ *
73
+ * Called during rotation to delete the oldest log and prepare for a new current log.
74
+ */
75
+ cleanup() {
76
+ const fileName = this.getFileName(this.maxEntries - 1);
77
+ if (fs.existsSync(fileName))
78
+ fs.unlinkSync(fileName);
79
+ this.buffer.end();
80
+ }
81
+ /**
82
+ * Prepares a new log file by creating a write stream.
83
+ *
84
+ * Opens the current log file (index 0) in append mode.
85
+ */
86
+ prepare() {
87
+ this.buffer = fs.createWriteStream(this.getFileName(), { flags: 'a' });
88
+ }
89
+ }
@@ -0,0 +1,31 @@
1
+ import { LogLevel, LogParam } from "./types.js";
2
+ import { LogClient } from "./LogClient.js";
3
+ /**
4
+ * Log client that outputs to console with special handling for different value types.
5
+ *
6
+ * Uses a simplified prefix format and handles various JavaScript types appropriately:
7
+ * - Errors: Extracts stack trace
8
+ * - Objects: JSON stringification
9
+ * - Primitives: Direct output
10
+ * - Functions/Symbols/BigInt: Type name only
11
+ */
12
+ declare class LogClient_Function_class extends LogClient {
13
+ constructor();
14
+ /**
15
+ * Outputs log messages with type-specific formatting.
16
+ *
17
+ * Handles different value types appropriately:
18
+ * - Errors: Uses stack trace extraction
19
+ * - Objects: JSON stringification
20
+ * - Primitives: Direct string conversion
21
+ * - Functions/Symbols/BigInt: Outputs type name only
22
+ *
23
+ * @param level - Log level
24
+ * @param bold - Whether to apply bold formatting (not used in this implementation)
25
+ * @param prefix - Composed prefix string
26
+ * @param toLog - Array of values to log
27
+ */
28
+ protected logMessage(level: LogLevel, bold: boolean, prefix: string, toLog: LogParam[]): void;
29
+ }
30
+ export declare const LogClient_Function: LogClient_Function_class;
31
+ export {};
@@ -0,0 +1,63 @@
1
+ /*
2
+ * @nu-art/logger - Flexible logging infrastructure with multiple output targets
3
+ * Copyright (C) 2024 Adam van der Kruk aka TacB0sS
4
+ * Licensed under the Apache License, Version 2.0
5
+ */
6
+ import { LogClient } from "./LogClient.js";
7
+ import { _logger_logException } from "./utils.js";
8
+ /**
9
+ * Log client that outputs to console with special handling for different value types.
10
+ *
11
+ * Uses a simplified prefix format and handles various JavaScript types appropriately:
12
+ * - Errors: Extracts stack trace
13
+ * - Objects: JSON stringification
14
+ * - Primitives: Direct output
15
+ * - Functions/Symbols/BigInt: Type name only
16
+ */
17
+ class LogClient_Function_class extends LogClient {
18
+ constructor() {
19
+ super();
20
+ this.setComposer((tag, level) => `${level} ${tag}: `);
21
+ }
22
+ /**
23
+ * Outputs log messages with type-specific formatting.
24
+ *
25
+ * Handles different value types appropriately:
26
+ * - Errors: Uses stack trace extraction
27
+ * - Objects: JSON stringification
28
+ * - Primitives: Direct string conversion
29
+ * - Functions/Symbols/BigInt: Outputs type name only
30
+ *
31
+ * @param level - Log level
32
+ * @param bold - Whether to apply bold formatting (not used in this implementation)
33
+ * @param prefix - Composed prefix string
34
+ * @param toLog - Array of values to log
35
+ */
36
+ logMessage(level, bold, prefix, toLog) {
37
+ for (const logParam of toLog) {
38
+ if (logParam)
39
+ // @ts-ignore
40
+ if (logParam.stack) {
41
+ console.log(`${prefix}${_logger_logException(logParam)}`);
42
+ continue;
43
+ }
44
+ switch (typeof logParam) {
45
+ case "undefined":
46
+ case "function":
47
+ case "symbol":
48
+ case "bigint":
49
+ console.log(`${prefix}${typeof logParam}`);
50
+ continue;
51
+ case "boolean":
52
+ case "number":
53
+ case "string":
54
+ console.log(`${prefix}${logParam}`);
55
+ continue;
56
+ case "object":
57
+ console.log(`${prefix}${JSON.stringify(logParam)}`);
58
+ continue;
59
+ }
60
+ }
61
+ }
62
+ }
63
+ export const LogClient_Function = new LogClient_Function_class();
@@ -0,0 +1,88 @@
1
+ import { LogClient_BaseRotate } from './LogClient_BaseRotate.js';
2
+ import { LogLevel, LogParam } from './types.js';
3
+ /**
4
+ * Log client that stores logs in memory buffers with rotation support.
5
+ *
6
+ * Maintains an array of string buffers that rotate when the current buffer exceeds maxBufferSize.
7
+ * Useful for in-memory log aggregation, testing, or when you need programmatic access to logs.
8
+ *
9
+ * Supports:
10
+ * - Log transformation via `setLogTransformer()`
11
+ * - Callbacks when logs are appended via `setLogAppendedListener()`
12
+ * - Color code preservation via `keepLogsNaturalColors()`
13
+ */
14
+ export declare class LogClient_MemBuffer extends LogClient_BaseRotate {
15
+ /** If true, preserves natural colors in log output (disables ANSI color codes) */
16
+ private keepNaturalColors;
17
+ /** Array of log buffers, where index 0 is the current buffer */
18
+ readonly buffers: string[];
19
+ /** Optional callback invoked when a log is appended */
20
+ private onLogAppended?;
21
+ /** Optional function to transform log strings before storage */
22
+ private logTransformer?;
23
+ /**
24
+ * Creates a new memory buffer log client.
25
+ *
26
+ * @param name - Identifier for this log client
27
+ * @param maxBuffers - Maximum number of rotated buffers to keep (default: 10)
28
+ * @param maxBufferSize - Maximum buffer size in bytes before rotation (default: 1MB)
29
+ */
30
+ constructor(name: string, maxBuffers?: number, maxBufferSize?: number);
31
+ /**
32
+ * Sets a function to transform log strings before they are stored.
33
+ *
34
+ * The transformer receives the log content (without prefix) and can modify it.
35
+ * Useful for sanitization, formatting, or filtering sensitive data.
36
+ *
37
+ * @param logTransformer - Function that transforms log strings
38
+ */
39
+ setLogTransformer(logTransformer: (log: string) => string): void;
40
+ /**
41
+ * Sets a callback to be invoked whenever a log is appended to the buffer.
42
+ *
43
+ * Useful for real-time log monitoring or triggering actions when logs are written.
44
+ *
45
+ * @param onLogAppended - Function to call when a log is appended
46
+ */
47
+ setLogAppendedListener(onLogAppended: VoidFunction): void;
48
+ /**
49
+ * Processes log message with color codes and optional transformation.
50
+ *
51
+ * Applies ANSI color codes, transforms the log if a transformer is set, and
52
+ * formats with proper indentation.
53
+ *
54
+ * @param level - Log level
55
+ * @param bold - Whether to apply bold formatting
56
+ * @param prefix - Composed prefix string
57
+ * @param toLog - Array of values to log
58
+ * @returns Formatted log string
59
+ */
60
+ protected processLogMessage(level: LogLevel, bold: boolean, prefix: string, toLog: LogParam[]): string;
61
+ /**
62
+ * Appends a log message to the current buffer and invokes the callback.
63
+ *
64
+ * @param log - Formatted log string (includes newline)
65
+ */
66
+ protected printLogMessage(log: string): void;
67
+ /**
68
+ * No cleanup needed for memory buffers (they're just strings).
69
+ */
70
+ protected cleanup(): void;
71
+ /**
72
+ * Rotates buffers by copying the source buffer to the destination index.
73
+ *
74
+ * @param fromIndex - Source buffer index
75
+ * @param toIndex - Destination buffer index
76
+ */
77
+ protected rotateBuffer(fromIndex: number, toIndex: number): void;
78
+ /**
79
+ * Prepares a new buffer by clearing the current one.
80
+ */
81
+ protected prepare(): void;
82
+ /**
83
+ * Controls whether natural colors in log output are preserved.
84
+ *
85
+ * @param keepNaturalColors - If true, disables color codes. Defaults to true.
86
+ */
87
+ keepLogsNaturalColors(keepNaturalColors?: boolean): void;
88
+ }
@@ -0,0 +1,139 @@
1
+ /*
2
+ * @nu-art/logger - Flexible logging infrastructure with multiple output targets
3
+ * Copyright (C) 2024 Adam van der Kruk aka TacB0sS
4
+ * Licensed under the Apache License, Version 2.0
5
+ */
6
+ import { LogClient_BaseRotate } from './LogClient_BaseRotate.js';
7
+ import { LogLevel } from './types.js';
8
+ import { _logger_convertLogParamsToStrings, _logger_indentNewLineBy } from './utils.js';
9
+ import { NoColor } from './LogClient_Terminal.js';
10
+ function getColor(level, bold = false) {
11
+ let color;
12
+ switch (level) {
13
+ case LogLevel.Verbose:
14
+ color = '\x1b[90m';
15
+ break;
16
+ case LogLevel.Debug:
17
+ color = '\x1b[34m';
18
+ break;
19
+ case LogLevel.Info:
20
+ color = '\x1b[32m';
21
+ break;
22
+ case LogLevel.Warning:
23
+ color = '\x1b[33m';
24
+ break;
25
+ case LogLevel.Error:
26
+ color = '\x1b[31m';
27
+ break;
28
+ }
29
+ return color + (bold ? '\x1b[1m' : '');
30
+ }
31
+ /**
32
+ * Log client that stores logs in memory buffers with rotation support.
33
+ *
34
+ * Maintains an array of string buffers that rotate when the current buffer exceeds maxBufferSize.
35
+ * Useful for in-memory log aggregation, testing, or when you need programmatic access to logs.
36
+ *
37
+ * Supports:
38
+ * - Log transformation via `setLogTransformer()`
39
+ * - Callbacks when logs are appended via `setLogAppendedListener()`
40
+ * - Color code preservation via `keepLogsNaturalColors()`
41
+ */
42
+ export class LogClient_MemBuffer extends LogClient_BaseRotate {
43
+ /** If true, preserves natural colors in log output (disables ANSI color codes) */
44
+ keepNaturalColors = false;
45
+ /** Array of log buffers, where index 0 is the current buffer */
46
+ buffers = [''];
47
+ /** Optional callback invoked when a log is appended */
48
+ onLogAppended;
49
+ /** Optional function to transform log strings before storage */
50
+ logTransformer;
51
+ /**
52
+ * Creates a new memory buffer log client.
53
+ *
54
+ * @param name - Identifier for this log client
55
+ * @param maxBuffers - Maximum number of rotated buffers to keep (default: 10)
56
+ * @param maxBufferSize - Maximum buffer size in bytes before rotation (default: 1MB)
57
+ */
58
+ constructor(name, maxBuffers = 10, maxBufferSize = 1024 * 1024) {
59
+ super(name, maxBuffers, maxBufferSize);
60
+ }
61
+ /**
62
+ * Sets a function to transform log strings before they are stored.
63
+ *
64
+ * The transformer receives the log content (without prefix) and can modify it.
65
+ * Useful for sanitization, formatting, or filtering sensitive data.
66
+ *
67
+ * @param logTransformer - Function that transforms log strings
68
+ */
69
+ setLogTransformer(logTransformer) {
70
+ this.logTransformer = logTransformer;
71
+ }
72
+ /**
73
+ * Sets a callback to be invoked whenever a log is appended to the buffer.
74
+ *
75
+ * Useful for real-time log monitoring or triggering actions when logs are written.
76
+ *
77
+ * @param onLogAppended - Function to call when a log is appended
78
+ */
79
+ setLogAppendedListener(onLogAppended) {
80
+ this.onLogAppended = onLogAppended;
81
+ }
82
+ /**
83
+ * Processes log message with color codes and optional transformation.
84
+ *
85
+ * Applies ANSI color codes, transforms the log if a transformer is set, and
86
+ * formats with proper indentation.
87
+ *
88
+ * @param level - Log level
89
+ * @param bold - Whether to apply bold formatting
90
+ * @param prefix - Composed prefix string
91
+ * @param toLog - Array of values to log
92
+ * @returns Formatted log string
93
+ */
94
+ processLogMessage(level, bold, prefix, toLog) {
95
+ const color = getColor(level, bold);
96
+ let log = _logger_convertLogParamsToStrings(toLog).join(' ');
97
+ const linePrefix = `${color}${prefix}${this.keepNaturalColors ? NoColor : ''}`;
98
+ if (this.logTransformer)
99
+ log = this.logTransformer(log);
100
+ return _logger_indentNewLineBy(linePrefix, log);
101
+ }
102
+ /**
103
+ * Appends a log message to the current buffer and invokes the callback.
104
+ *
105
+ * @param log - Formatted log string (includes newline)
106
+ */
107
+ printLogMessage(log) {
108
+ this.buffers[0] += log;
109
+ this.onLogAppended?.();
110
+ }
111
+ /**
112
+ * No cleanup needed for memory buffers (they're just strings).
113
+ */
114
+ cleanup() {
115
+ }
116
+ /**
117
+ * Rotates buffers by copying the source buffer to the destination index.
118
+ *
119
+ * @param fromIndex - Source buffer index
120
+ * @param toIndex - Destination buffer index
121
+ */
122
+ rotateBuffer(fromIndex, toIndex) {
123
+ this.buffers[toIndex] = this.buffers[fromIndex];
124
+ }
125
+ /**
126
+ * Prepares a new buffer by clearing the current one.
127
+ */
128
+ prepare() {
129
+ this.buffers[0] = '';
130
+ }
131
+ /**
132
+ * Controls whether natural colors in log output are preserved.
133
+ *
134
+ * @param keepNaturalColors - If true, disables color codes. Defaults to true.
135
+ */
136
+ keepLogsNaturalColors(keepNaturalColors = true) {
137
+ this.keepNaturalColors = keepNaturalColors;
138
+ }
139
+ }
@@ -0,0 +1,49 @@
1
+ import { LogLevel, LogParam } from './types.js';
2
+ import { LogClient } from './LogClient.js';
3
+ /**
4
+ * ANSI escape code to reset terminal color formatting.
5
+ *
6
+ * Used to reset color codes after applying colored log output.
7
+ */
8
+ export declare const NoColor = "\u001B[0m";
9
+ /**
10
+ * Log client implementation for terminal/console output with ANSI color codes.
11
+ *
12
+ * Outputs colored log messages to the console using ANSI escape sequences.
13
+ * Different log levels are displayed in different colors for visual distinction.
14
+ */
15
+ declare class LogClient_Terminal_class extends LogClient {
16
+ /** If true, preserves natural colors in log output (disables color codes) */
17
+ private keepNaturalColors;
18
+ /**
19
+ * Gets the ANSI color code for a log level.
20
+ *
21
+ * @param level - Log level
22
+ * @param bold - Whether to apply bold formatting
23
+ * @returns ANSI escape sequence for the color
24
+ */
25
+ getColor(level: LogLevel, bold?: boolean): string;
26
+ /**
27
+ * Outputs a log message to the terminal with color formatting.
28
+ *
29
+ * Converts all log parameters to strings, applies color codes, and outputs
30
+ * to console.log. Always resets color at the end of the line.
31
+ *
32
+ * @param level - Log level
33
+ * @param bold - Whether to apply bold formatting
34
+ * @param prefix - Composed prefix string
35
+ * @param toLog - Array of values to log
36
+ */
37
+ protected logMessage(level: LogLevel, bold: boolean, prefix: string, toLog: LogParam[]): void;
38
+ /**
39
+ * Controls whether natural colors in log output are preserved.
40
+ *
41
+ * When enabled, disables ANSI color codes to preserve any colors that might
42
+ * be present in the log content itself.
43
+ *
44
+ * @param keepNaturalColors - If true, disables color codes. Defaults to true.
45
+ */
46
+ keepLogsNaturalColors(keepNaturalColors?: boolean): void;
47
+ }
48
+ export declare const LogClient_Terminal: LogClient_Terminal_class;
49
+ export {};
@@ -0,0 +1,81 @@
1
+ /*
2
+ * @nu-art/logger - Flexible logging infrastructure with multiple output targets
3
+ * Copyright (C) 2024 Adam van der Kruk aka TacB0sS
4
+ * Licensed under the Apache License, Version 2.0
5
+ */
6
+ import { LogLevel } from './types.js';
7
+ import { LogClient } from './LogClient.js';
8
+ import { _logger_convertLogParamsToStrings, _logger_indentNewLineBy } from './utils.js';
9
+ /**
10
+ * ANSI escape code to reset terminal color formatting.
11
+ *
12
+ * Used to reset color codes after applying colored log output.
13
+ */
14
+ export const NoColor = '\x1b[0m';
15
+ /**
16
+ * Log client implementation for terminal/console output with ANSI color codes.
17
+ *
18
+ * Outputs colored log messages to the console using ANSI escape sequences.
19
+ * Different log levels are displayed in different colors for visual distinction.
20
+ */
21
+ class LogClient_Terminal_class extends LogClient {
22
+ /** If true, preserves natural colors in log output (disables color codes) */
23
+ keepNaturalColors = false;
24
+ /**
25
+ * Gets the ANSI color code for a log level.
26
+ *
27
+ * @param level - Log level
28
+ * @param bold - Whether to apply bold formatting
29
+ * @returns ANSI escape sequence for the color
30
+ */
31
+ getColor(level, bold = false) {
32
+ let color;
33
+ switch (level) {
34
+ case LogLevel.Verbose:
35
+ color = '\x1b[90m';
36
+ break;
37
+ case LogLevel.Debug:
38
+ color = '\x1b[34m';
39
+ break;
40
+ case LogLevel.Info:
41
+ color = '\x1b[32m';
42
+ break;
43
+ case LogLevel.Warning:
44
+ color = '\x1b[33m';
45
+ break;
46
+ case LogLevel.Error:
47
+ color = '\x1b[31m';
48
+ break;
49
+ }
50
+ return color + (bold ? '\x1b[1m' : '');
51
+ }
52
+ /**
53
+ * Outputs a log message to the terminal with color formatting.
54
+ *
55
+ * Converts all log parameters to strings, applies color codes, and outputs
56
+ * to console.log. Always resets color at the end of the line.
57
+ *
58
+ * @param level - Log level
59
+ * @param bold - Whether to apply bold formatting
60
+ * @param prefix - Composed prefix string
61
+ * @param toLog - Array of values to log
62
+ */
63
+ logMessage(level, bold, prefix, toLog) {
64
+ const color = this.getColor(level, bold);
65
+ const paramsAsStrings = _logger_convertLogParamsToStrings(toLog);
66
+ const linePrefix = `${color}${prefix}${this.keepNaturalColors ? NoColor : ''}`;
67
+ console.log(_logger_indentNewLineBy(linePrefix, paramsAsStrings.join(' ')) + NoColor);
68
+ }
69
+ /**
70
+ * Controls whether natural colors in log output are preserved.
71
+ *
72
+ * When enabled, disables ANSI color codes to preserve any colors that might
73
+ * be present in the log content itself.
74
+ *
75
+ * @param keepNaturalColors - If true, disables color codes. Defaults to true.
76
+ */
77
+ keepLogsNaturalColors(keepNaturalColors = true) {
78
+ this.keepNaturalColors = keepNaturalColors;
79
+ }
80
+ }
81
+ export const LogClient_Terminal = new LogClient_Terminal_class();