vloggo 1.0.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,274 @@
1
+ # VLoggo
2
+
3
+ Logging library for Node.js and Bun with file rotation, SMTP notifications, and JSON output support.
4
+
5
+ ## Features
6
+
7
+ - **Multiple log levels**: INFO, WARN, DEBUG, ERROR, FATAL
8
+ - **Automatic file rotation**: Daily rotation with configurable retention
9
+ - **SMTP notifications**: Email alerts for fatal errors with throttling
10
+ - **JSON output**: Optional structured logging in JSONL format
11
+ - **Caller tracking**: Automatic source file and line number tracking
12
+ - **TypeScript support**: Full type definitions included
13
+ - **Zero configuration**: Works out of the box with sensible defaults
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install @vinialx/vloggo
19
+ ```
20
+
21
+ ```bash
22
+ bun add @vinialx/vloggo
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```typescript
28
+ import { VLoggo } from "@vinialx/vloggo";
29
+
30
+ const logger = new VLoggo({ client: "MyApp" });
31
+
32
+ logger.info("APP_START", "Application started");
33
+ logger.warn("HIGH_MEMORY", "Memory usage above 80%");
34
+ logger.error("API_FAIL", "External API request failed");
35
+ logger.fatal("DB_DOWN", "Database connection lost");
36
+ ```
37
+
38
+ ## Configuration
39
+
40
+ ### Basic Configuration
41
+
42
+ ```typescript
43
+ const logger = new VLoggo({
44
+ client: "MyApp", // Application name
45
+ console: true, // Enable console output
46
+ debug: false, // Enable debug logs
47
+ json: false, // Enable JSON output
48
+ });
49
+ ```
50
+
51
+ ### File Configuration
52
+
53
+ ```typescript
54
+ const logger = new VLoggo({
55
+ client: "MyApp",
56
+ directory: {
57
+ txt: "/var/log/myapp", // Text log directory
58
+ json: "/var/log/myapp/json", // JSON log directory
59
+ },
60
+ filecount: {
61
+ txt: 31, // Keep 31 days of text logs
62
+ json: 7, // Keep 7 days of JSON logs
63
+ },
64
+ });
65
+ ```
66
+
67
+ ### SMTP Configuration
68
+
69
+ ```typescript
70
+ const logger = new VLoggo({
71
+ client: "MyApp",
72
+ smtp: {
73
+ host: "smtp.gmail.com",
74
+ port: 465,
75
+ secure: true,
76
+ username: "your-email@gmail.com",
77
+ password: "your-password",
78
+ from: "logs@myapp.com",
79
+ to: "admin@myapp.com", // Can be string or array
80
+ },
81
+ throttle: 300000, // Min 5 minutes between emails
82
+ });
83
+ ```
84
+
85
+ ### Environment Variables
86
+
87
+ SMTP can be configured via environment variables:
88
+
89
+ ```bash
90
+ SMTP_HOST=smtp.gmail.com
91
+ SMTP_PORT=465
92
+ SMTP_USERNAME=your-email@gmail.com
93
+ SMTP_PASSWORD=your-password
94
+ SMTP_FROM=logs@myapp.com
95
+ SMTP_TO=admin@myapp.com
96
+ ```
97
+
98
+ ## API Reference
99
+
100
+ ### Constructor
101
+
102
+ ```typescript
103
+ new VLoggo(options?: Partial<VLoggoConfig>)
104
+ ```
105
+
106
+ **Options:**
107
+
108
+ - `client`: Application name (default: 'VLoggo')
109
+ - `console`: Enable console output (default: true)
110
+ - `debug`: Enable debug mode (default: false)
111
+ - `json`: Enable JSON output (default: false)
112
+ - `directory`: Log directories (default: ~/[client]/logs)
113
+ - `filecount`: Retention days (default: { txt: 31, json: 31 })
114
+ - `smtp`: SMTP configuration (optional)
115
+ - `throttle`: Email throttle in ms (default: 30000)
116
+
117
+ ### Logging Methods
118
+
119
+ ```typescript
120
+ logger.info(code: string, message: string): void
121
+ logger.warn(code: string, message: string): void
122
+ logger.debug(code: string, message: string): void
123
+ logger.error(code: string, message: string): void
124
+ logger.fatal(code: string, message: string): void
125
+ ```
126
+
127
+ **Parameters:**
128
+
129
+ - `code`: Short identifier for the log entry
130
+ - `message`: Detailed log message
131
+
132
+ ### Configuration Access
133
+
134
+ ```typescript
135
+ // Read configuration
136
+ logger.config.client; // string
137
+ logger.config.debug; // boolean
138
+ logger.config.console; // boolean
139
+ logger.config.json; // boolean
140
+ logger.config.directory; // VLoggoDirectory
141
+ logger.config.filecount; // VLoggoFilecount
142
+ logger.config.notify; // boolean
143
+ logger.config.smtp; // VLoggoSMTPConfig | undefined
144
+ logger.config.throttle; // number
145
+
146
+ // Clone configuration
147
+ const newConfig = logger.config.clone({ client: "NewApp" });
148
+
149
+ // Update configuration
150
+ logger.config.update({ debug: true, throttle: 60000 });
151
+ ```
152
+
153
+ ## Log Format
154
+
155
+ ### Text Format
156
+
157
+ ```
158
+ [MyApp] [03/11/2025 14:30:45] [INFO] [APP_START] [server.ts:15]: Application started
159
+ ```
160
+
161
+ ### JSON Format (JSONL)
162
+
163
+ ```json
164
+ {
165
+ "client": "MyApp",
166
+ "timestamp": "2025-11-03T14:30:45.123Z",
167
+ "level": "INFO",
168
+ "code": "APP_START",
169
+ "caller": "server.ts:15",
170
+ "message": "Application started"
171
+ }
172
+ ```
173
+
174
+ ## File Rotation
175
+
176
+ - Logs rotate daily at midnight
177
+ - Old logs are automatically deleted based on `filecount` setting
178
+ - Separate rotation for text and JSON logs
179
+ - Rotation happens asynchronously without blocking logging
180
+
181
+ ## Email Notifications
182
+
183
+ - Only sent for `fatal()` logs
184
+ - Throttled to prevent spam (configurable via `throttle`)
185
+ - Includes timestamp, code, caller location, and message
186
+ - HTML formatted emails
187
+
188
+ ## Examples
189
+
190
+ ### Express.js Integration
191
+
192
+ ```typescript
193
+ import express from "express";
194
+ import { VLoggo } from "@vinialx/vloggo";
195
+
196
+ const app = express();
197
+ const logger = new VLoggo({ client: "API" });
198
+
199
+ app.use((req, res, next) => {
200
+ logger.info("REQUEST", `${req.method} ${req.path}`);
201
+ next();
202
+ });
203
+
204
+ app.use((err, req, res, next) => {
205
+ logger.error("ERROR", err.message);
206
+ res.status(500).json({ error: "Internal Server Error" });
207
+ });
208
+ ```
209
+
210
+ ### Database Connection Monitoring
211
+
212
+ ```typescript
213
+ async function connectDatabase() {
214
+ try {
215
+ await db.connect();
216
+ logger.info("DB_CONNECT", "Database connected successfully");
217
+ } catch (error) {
218
+ logger.fatal("DB_CONNECT_FAIL", error.message);
219
+ process.exit(1);
220
+ }
221
+ }
222
+ ```
223
+
224
+ ### Scheduled Task Logging
225
+
226
+ ```typescript
227
+ import cron from "node-cron";
228
+
229
+ cron.schedule("0 0 * * *", () => {
230
+ logger.info("CRON_START", "Daily cleanup task started");
231
+
232
+ try {
233
+ performCleanup();
234
+ logger.info("CRON_SUCCESS", "Daily cleanup completed");
235
+ } catch (error) {
236
+ logger.error("CRON_FAIL", error.message);
237
+ }
238
+ });
239
+ ```
240
+
241
+ ## TypeScript Support
242
+
243
+ Full TypeScript definitions are included:
244
+
245
+ ```typescript
246
+ import { VLoggo, VLoggoConfig, LogLevel, LogEntry } from "vloggo";
247
+
248
+ const config: Partial<VLoggoConfig> = {
249
+ client: "TypeScriptApp",
250
+ debug: true,
251
+ };
252
+
253
+ const logger = new VLoggo(config);
254
+ ```
255
+
256
+ ## Performance Considerations
257
+
258
+ - File writes are synchronous for data integrity
259
+ - Rotation is asynchronous to avoid blocking
260
+ - Email sending is asynchronous with error handling
261
+ - Minimal overhead for disabled features
262
+
263
+ ## License
264
+
265
+ MIT
266
+
267
+ ## Support
268
+
269
+ For issues and feature requests, visit: https://github.com/vinialx/vloggo/issues
270
+
271
+
272
+ ## Author
273
+
274
+ Email: vini.aloise.silva@gmail.com
@@ -0,0 +1,159 @@
1
+ import { VLoggoConfig, VLoggoSMTPConfig, VLoggoDirectory, VLoggoFilecount } from "../interfaces/interfaces";
2
+ /**
3
+ * Configuration manager for VLoggo.
4
+ * Manages all settings including SMTP, file rotation and debugging.
5
+ *
6
+ * @class Config
7
+ */
8
+ declare class Config {
9
+ private _client;
10
+ private _json;
11
+ private _debug;
12
+ private _console;
13
+ private _filecount;
14
+ private _directory;
15
+ private _notify;
16
+ private _throttle;
17
+ private _smtp;
18
+ private format;
19
+ /**
20
+ * Creates a new Config instance.
21
+ * Loads configuration from options or environment variables.
22
+ *
23
+ * @param {Partial<VLoggoConfig>} [options] - Optional configuration overrides
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // Minimal config
28
+ * const config = new Config({ client: 'MyApp' });
29
+ *
30
+ * // With SMTP
31
+ * const config = new Config({
32
+ * client: 'MyApp',
33
+ * smtp: { host: '...', port: 465, ... }
34
+ * });
35
+ * ```
36
+ */
37
+ constructor(options?: Partial<VLoggoConfig>);
38
+ /**
39
+ * Loads SMTP configuration from environment variables.
40
+ * Validates port number and sets secure flag based on port 465.
41
+ * Disables notifications if any required environment variable is missing or invalid.
42
+ *
43
+ * Required environment variables:
44
+ * - SMTP_TO: Recipient email address
45
+ * - SMTP_FROM: Sender email address
46
+ * - SMTP_HOST: SMTP server hostname
47
+ * - SMTP_PORT: SMTP server port
48
+ * - SMTP_USERNAME: SMTP authentication username
49
+ * - SMTP_PASSWORD: SMTP authentication password
50
+ *
51
+ * @private
52
+ * @returns {void}
53
+ */
54
+ private loadSMTPFromEnv;
55
+ /**
56
+ * Updates configuration properties.
57
+ * Only updates properties that are provided in the options parameter.
58
+ * Supports partial SMTP configuration updates - merges with existing SMTP settings.
59
+ *
60
+ * @param {Partial<VLoggoConfig> & { smtp?: Partial<VLoggoSMTPConfig> }} options - Configuration properties to update
61
+ * @returns {void}
62
+ *
63
+ * @example
64
+ * ```typescript
65
+ * // Update simple properties
66
+ * config.update({ debug: false, throttle: 60000 });
67
+ *
68
+ * // Update only specific SMTP properties
69
+ * config.update({
70
+ * smtp: {
71
+ * host: 'new-smtp.example.com',
72
+ * port: 587
73
+ * }
74
+ * });
75
+ * ```
76
+ */
77
+ update(options: Partial<VLoggoConfig> & {
78
+ smtp?: Partial<VLoggoSMTPConfig>;
79
+ }): void;
80
+ /**
81
+ * Creates a clone of this config with optional overrides.
82
+ * The original config is not modified.
83
+ *
84
+ * @param {Partial<VLoggoConfig>} [overrides] - Properties to override in the cloned config
85
+ * @returns {Config} New Config instance with overrides applied
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * const baseConfig = new Config();
90
+ * const apiConfig = baseConfig.clone({ client: 'API' });
91
+ * ```
92
+ */
93
+ clone(overrides?: Partial<VLoggoConfig>): Config;
94
+ /**
95
+ * Gets the client/application name.
96
+ *
97
+ * @readonly
98
+ * @returns {string} Client/application name
99
+ */
100
+ get client(): string;
101
+ /**
102
+ * Gets whether json mode is enabled.
103
+ *
104
+ * @readonly
105
+ * @returns {boolean} True if debug mode is enabled
106
+ */
107
+ get json(): boolean;
108
+ /**
109
+ * Gets whether debug mode is enabled.
110
+ *
111
+ * @readonly
112
+ * @returns {boolean} True if debug mode is enabled
113
+ */
114
+ get debug(): boolean;
115
+ /**
116
+ * Gets whether console output is enabled.
117
+ *
118
+ * @readonly
119
+ * @returns {boolean} True if console output is enabled
120
+ */
121
+ get console(): boolean;
122
+ /**
123
+ * Gets the maximum number of log files to keep.
124
+ *
125
+ * @readonly
126
+ * @returns {number} Maximum file count before rotation
127
+ */
128
+ get filecount(): VLoggoFilecount;
129
+ /**
130
+ * Gets the log directory path.
131
+ *
132
+ * @readonly
133
+ * @returns {string} Absolute path to log directory
134
+ */
135
+ get directory(): VLoggoDirectory;
136
+ /**
137
+ * Gets whether email notifications are enabled.
138
+ *
139
+ * @readonly
140
+ * @returns {boolean} True if email notifications are enabled
141
+ */
142
+ get notify(): boolean;
143
+ /**
144
+ * Gets the SMTP configuration.
145
+ *
146
+ * @readonly
147
+ * @returns {VLoggoSMTPConfig | undefined} SMTP config object or undefined if not configured
148
+ */
149
+ get smtp(): VLoggoSMTPConfig | undefined;
150
+ /**
151
+ * Gets the email throttle time in milliseconds.
152
+ *
153
+ * @readonly
154
+ * @returns {number} Throttle time in milliseconds
155
+ */
156
+ get throttle(): number;
157
+ }
158
+ export declare const defaultConfig: VLoggoConfig;
159
+ export default Config;
@@ -0,0 +1,291 @@
1
+ import * as os from "os";
2
+ import * as path from "path";
3
+ import FormatService from "../internal/formatService";
4
+ /**
5
+ * Configuration manager for VLoggo.
6
+ * Manages all settings including SMTP, file rotation and debugging.
7
+ *
8
+ * @class Config
9
+ */
10
+ class Config {
11
+ _client;
12
+ _json;
13
+ _debug;
14
+ _console;
15
+ _filecount;
16
+ _directory;
17
+ _notify;
18
+ _throttle;
19
+ _smtp = undefined;
20
+ format = new FormatService();
21
+ /**
22
+ * Creates a new Config instance.
23
+ * Loads configuration from options or environment variables.
24
+ *
25
+ * @param {Partial<VLoggoConfig>} [options] - Optional configuration overrides
26
+ *
27
+ * @example
28
+ * ```typescript
29
+ * // Minimal config
30
+ * const config = new Config({ client: 'MyApp' });
31
+ *
32
+ * // With SMTP
33
+ * const config = new Config({
34
+ * client: 'MyApp',
35
+ * smtp: { host: '...', port: 465, ... }
36
+ * });
37
+ * ```
38
+ */
39
+ constructor(options) {
40
+ this._client = options?.client || process.env.CLIENT_NAME || "VLoggo";
41
+ this._json = options?.json ?? false;
42
+ this._debug = options?.debug ?? false;
43
+ this._console = options?.console ?? true;
44
+ this._filecount = options?.filecount ?? { txt: 31, json: 31 };
45
+ this._directory = options?.directory || {
46
+ txt: path.resolve(os.homedir(), this._client, "logs"),
47
+ json: path.resolve(os.homedir(), this._client, "json"),
48
+ };
49
+ this._notify = options?.notify ?? false;
50
+ this._throttle = options?.throttle ?? 30000;
51
+ if (options?.smtp) {
52
+ this._smtp = options.smtp;
53
+ this._notify = true;
54
+ }
55
+ else {
56
+ this.loadSMTPFromEnv();
57
+ }
58
+ }
59
+ /**
60
+ * Loads SMTP configuration from environment variables.
61
+ * Validates port number and sets secure flag based on port 465.
62
+ * Disables notifications if any required environment variable is missing or invalid.
63
+ *
64
+ * Required environment variables:
65
+ * - SMTP_TO: Recipient email address
66
+ * - SMTP_FROM: Sender email address
67
+ * - SMTP_HOST: SMTP server hostname
68
+ * - SMTP_PORT: SMTP server port
69
+ * - SMTP_USERNAME: SMTP authentication username
70
+ * - SMTP_PASSWORD: SMTP authentication password
71
+ *
72
+ * @private
73
+ * @returns {void}
74
+ */
75
+ loadSMTPFromEnv() {
76
+ const to = process.env.SMTP_TO;
77
+ const from = process.env.SMTP_FROM;
78
+ const host = process.env.SMTP_HOST;
79
+ const portStr = process.env.SMTP_PORT;
80
+ const username = process.env.SMTP_USERNAME;
81
+ const password = process.env.SMTP_PASSWORD;
82
+ if (!to || !from || !host || !portStr || !username || !password) {
83
+ console.warn(`[VLoggo] > [${this.client}] [${this.format.date()}] [WARN] : notification service disabled > missing configuration`);
84
+ this._notify = false;
85
+ return;
86
+ }
87
+ const port = parseInt(portStr);
88
+ if (isNaN(port) || port <= 0 || port > 65535) {
89
+ console.error(`[VLoggo] > [${this.client}] [${this.format.date()}] [ERROR] : notification service disabled > invalid port - ${portStr}.`);
90
+ this._notify = false;
91
+ return;
92
+ }
93
+ const secure = port === 465 ? true : false;
94
+ this._smtp = {
95
+ to,
96
+ from,
97
+ host,
98
+ port,
99
+ username,
100
+ password,
101
+ secure,
102
+ };
103
+ this._notify = true;
104
+ }
105
+ /**
106
+ * Updates configuration properties.
107
+ * Only updates properties that are provided in the options parameter.
108
+ * Supports partial SMTP configuration updates - merges with existing SMTP settings.
109
+ *
110
+ * @param {Partial<VLoggoConfig> & { smtp?: Partial<VLoggoSMTPConfig> }} options - Configuration properties to update
111
+ * @returns {void}
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * // Update simple properties
116
+ * config.update({ debug: false, throttle: 60000 });
117
+ *
118
+ * // Update only specific SMTP properties
119
+ * config.update({
120
+ * smtp: {
121
+ * host: 'new-smtp.example.com',
122
+ * port: 587
123
+ * }
124
+ * });
125
+ * ```
126
+ */
127
+ update(options) {
128
+ if (options.client) {
129
+ this._client = options.client;
130
+ }
131
+ if (options.json !== undefined) {
132
+ this._json = options.json;
133
+ }
134
+ if (options.debug !== undefined) {
135
+ this._debug = options.debug;
136
+ }
137
+ if (options.console !== undefined) {
138
+ this._console = options.console;
139
+ }
140
+ if (options.filecount) {
141
+ if (options.filecount.txt) {
142
+ this._filecount.txt = options.filecount.txt;
143
+ }
144
+ if (options.filecount.json) {
145
+ this._filecount.json = options.filecount.json;
146
+ }
147
+ }
148
+ if (options.directory) {
149
+ if (options.directory.txt) {
150
+ this._directory.txt = options.directory.txt;
151
+ }
152
+ if (options.directory.json) {
153
+ this._directory.json = options.directory.json;
154
+ }
155
+ }
156
+ if (options.notify !== undefined) {
157
+ this._notify = options.notify;
158
+ }
159
+ if (options.throttle) {
160
+ this._throttle = options.throttle;
161
+ }
162
+ if (options.smtp) {
163
+ this._smtp = {
164
+ ...this._smtp,
165
+ ...options.smtp,
166
+ };
167
+ }
168
+ }
169
+ /**
170
+ * Creates a clone of this config with optional overrides.
171
+ * The original config is not modified.
172
+ *
173
+ * @param {Partial<VLoggoConfig>} [overrides] - Properties to override in the cloned config
174
+ * @returns {Config} New Config instance with overrides applied
175
+ *
176
+ * @example
177
+ * ```typescript
178
+ * const baseConfig = new Config();
179
+ * const apiConfig = baseConfig.clone({ client: 'API' });
180
+ * ```
181
+ */
182
+ clone(overrides) {
183
+ return new Config({
184
+ client: overrides?.client ?? this._client,
185
+ json: overrides?.json ?? this._json,
186
+ debug: overrides?.debug ?? this._debug,
187
+ console: overrides?.console ?? this._console,
188
+ directory: overrides?.directory ?? this._directory,
189
+ filecount: overrides?.filecount ?? this._filecount,
190
+ throttle: overrides?.throttle ?? this._throttle,
191
+ notify: overrides?.notify ?? this._notify,
192
+ smtp: overrides?.smtp ?? this._smtp,
193
+ });
194
+ }
195
+ /**
196
+ * Gets the client/application name.
197
+ *
198
+ * @readonly
199
+ * @returns {string} Client/application name
200
+ */
201
+ get client() {
202
+ return this._client;
203
+ }
204
+ /**
205
+ * Gets whether json mode is enabled.
206
+ *
207
+ * @readonly
208
+ * @returns {boolean} True if debug mode is enabled
209
+ */
210
+ get json() {
211
+ return this._json;
212
+ }
213
+ /**
214
+ * Gets whether debug mode is enabled.
215
+ *
216
+ * @readonly
217
+ * @returns {boolean} True if debug mode is enabled
218
+ */
219
+ get debug() {
220
+ return this._debug;
221
+ }
222
+ /**
223
+ * Gets whether console output is enabled.
224
+ *
225
+ * @readonly
226
+ * @returns {boolean} True if console output is enabled
227
+ */
228
+ get console() {
229
+ return this._console;
230
+ }
231
+ /**
232
+ * Gets the maximum number of log files to keep.
233
+ *
234
+ * @readonly
235
+ * @returns {number} Maximum file count before rotation
236
+ */
237
+ get filecount() {
238
+ return this._filecount;
239
+ }
240
+ /**
241
+ * Gets the log directory path.
242
+ *
243
+ * @readonly
244
+ * @returns {string} Absolute path to log directory
245
+ */
246
+ get directory() {
247
+ return this._directory;
248
+ }
249
+ /**
250
+ * Gets whether email notifications are enabled.
251
+ *
252
+ * @readonly
253
+ * @returns {boolean} True if email notifications are enabled
254
+ */
255
+ get notify() {
256
+ return this._notify;
257
+ }
258
+ /**
259
+ * Gets the SMTP configuration.
260
+ *
261
+ * @readonly
262
+ * @returns {VLoggoSMTPConfig | undefined} SMTP config object or undefined if not configured
263
+ */
264
+ get smtp() {
265
+ return this._smtp;
266
+ }
267
+ /**
268
+ * Gets the email throttle time in milliseconds.
269
+ *
270
+ * @readonly
271
+ * @returns {number} Throttle time in milliseconds
272
+ */
273
+ get throttle() {
274
+ return this._throttle;
275
+ }
276
+ }
277
+ export const defaultConfig = {
278
+ client: "VLoggo",
279
+ json: false,
280
+ debug: false,
281
+ console: true,
282
+ filecount: { txt: 31, json: 31 },
283
+ directory: {
284
+ txt: path.resolve(os.homedir(), "VLoggo", "logs"),
285
+ json: path.resolve(os.homedir(), "VLoggo", "json"),
286
+ },
287
+ throttle: 30000,
288
+ notify: false, // Importante: false por padrão
289
+ smtp: undefined,
290
+ };
291
+ export default Config;