debug-lite-js 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,113 @@
1
+ # debug-lite-js
2
+
3
+ Utilitário Node.js para facilitar o debug de aplicações backend com logs estruturados, pretty print, timers e captura de erros.
4
+
5
+ ## Recursos
6
+
7
+ - Logs inteligentes com níveis `info`, `warn`, `error` e `debug`
8
+ - Timestamp em cada mensagem
9
+ - Cores no console com `chalk`
10
+ - Pretty print de objetos JSON e nested objects
11
+ - Debug condicional via `DEBUG=true`
12
+ - Timer de execução com `startTimer` / `endTimer`
13
+ - Função de captura de erros com stack trace formatado
14
+
15
+ ## Instalação
16
+
17
+ ```bash
18
+ npm install debug-lite-js
19
+ ```
20
+
21
+ ## Uso básico
22
+
23
+ ```javascript
24
+ const debug = require('debug-lite-js');
25
+
26
+ debug.info('Servidor iniciado');
27
+ debug.warn('Espaço em disco baixo');
28
+ debug.error('Erro inesperado');
29
+
30
+ debug.debug('Dados de depuração', { user: 'admin' });
31
+
32
+ debug.pretty({
33
+ user: 'admin',
34
+ roles: ['admin', 'editor'],
35
+ profile: { age: 30, active: true },
36
+ });
37
+ ```
38
+
39
+ ## Exemplo real em Express
40
+
41
+ ```javascript
42
+ const express = require('express');
43
+ const debug = require('debug-lite-js');
44
+
45
+ const app = express();
46
+ const port = process.env.PORT || 3000;
47
+
48
+ app.use(express.json());
49
+
50
+ app.use((req, res, next) => {
51
+ debug.info('Request recebida', { method: req.method, path: req.path });
52
+ if (debug.isDebugEnabled()) {
53
+ debug.pretty({ headers: req.headers, query: req.query, body: req.body });
54
+ }
55
+ next();
56
+ });
57
+
58
+ app.get('/', (req, res) => {
59
+ debug.startTimer('home-route');
60
+ res.send('Hello World');
61
+ debug.endTimer('home-route');
62
+ });
63
+
64
+ app.get('/users/:id', async (req, res) => {
65
+ const userId = req.params.id;
66
+ debug.info('Buscando usuário', userId);
67
+ debug.startTimer('fetch-user');
68
+
69
+ try {
70
+ // Simula busca de usuário
71
+ const user = { id: userId, name: 'Maria', role: 'admin' };
72
+ debug.pretty(user);
73
+ res.json(user);
74
+ } catch (error) {
75
+ debug.logError(error, 'Falha ao buscar usuário');
76
+ res.status(500).json({ error: 'Erro interno' });
77
+ } finally {
78
+ debug.endTimer('fetch-user');
79
+ }
80
+ });
81
+
82
+ app.use((err, req, res, next) => {
83
+ debug.logError(err, 'Erro de middleware');
84
+ res.status(500).json({ error: 'Erro interno do servidor' });
85
+ });
86
+
87
+ app.listen(port, () => {
88
+ debug.info(`Servidor Express rodando na porta ${port}`);
89
+ });
90
+ ```
91
+
92
+ ## Ativar logs de debug
93
+
94
+ ```bash
95
+ DEBUG=true node app.js
96
+ ```
97
+
98
+ ## API Exportada
99
+
100
+ - `log(level, message, ...meta)`
101
+ - `info(message, ...meta)`
102
+ - `warn(message, ...meta)`
103
+ - `error(message, ...meta)`
104
+ - `debug(message, ...meta)`
105
+ - `logError(error, message)`
106
+ - `isDebugEnabled()`
107
+ - `pretty(value, options)`
108
+ - `startTimer(label)`
109
+ - `endTimer(label, options)`
110
+
111
+ ---
112
+
113
+ `debug-lite-js` foi criado para tornar as rotinas de depuração mais visuais e rápidas no Node.js.
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "debug-lite-js",
3
+ "version": "1.0.0",
4
+ "description": "Utility module for improved Node.js debugging with structured logs, pretty printing, timers, and error capture.",
5
+ "main": "src/index.js",
6
+ "files": ["src", "README.md"],
7
+ "keywords": ["debug", "logger", "node", "pretty-print", "timer", "errors"],
8
+ "author": "",
9
+ "license": "MIT",
10
+ "dependencies": {
11
+ "chalk": "^4.1.2"
12
+ }
13
+ }
@@ -0,0 +1,21 @@
1
+ const chalk = require('chalk');
2
+ const util = require('util');
3
+
4
+ function pretty(value, options = {}) {
5
+ const defaultOptions = {
6
+ depth: 6,
7
+ colors: true,
8
+ compact: false,
9
+ sorted: true,
10
+ };
11
+
12
+ const config = Object.assign({}, defaultOptions, options);
13
+ const output = util.inspect(value, config);
14
+
15
+ console.log(chalk.cyan.bold('[PRETTY PRINT]'));
16
+ console.log(output);
17
+ }
18
+
19
+ module.exports = {
20
+ pretty,
21
+ };
package/src/index.js ADDED
@@ -0,0 +1,16 @@
1
+ const logger = require('./logger');
2
+ const formatter = require('./formatter');
3
+ const timer = require('./timer');
4
+
5
+ module.exports = {
6
+ log: logger.log,
7
+ info: logger.info,
8
+ warn: logger.warn,
9
+ error: logger.error,
10
+ debug: logger.debug,
11
+ logError: logger.logError,
12
+ isDebugEnabled: logger.isDebugEnabled,
13
+ pretty: formatter.pretty,
14
+ startTimer: timer.startTimer,
15
+ endTimer: timer.endTimer,
16
+ };
package/src/logger.js ADDED
@@ -0,0 +1,57 @@
1
+ const chalk = require('chalk');
2
+
3
+ const levels = {
4
+ info: { label: 'INFO', color: chalk.blue },
5
+ warn: { label: 'WARN', color: chalk.yellow },
6
+ error: { label: 'ERROR', color: chalk.red },
7
+ debug: { label: 'DEBUG', color: chalk.magenta },
8
+ };
9
+
10
+ function getTimestamp() {
11
+ return new Date().toISOString();
12
+ }
13
+
14
+ function isDebugEnabled() {
15
+ const value = process.env.DEBUG;
16
+ return value === 'true' || value === '1' || value === 'all' || value === 'yes';
17
+ }
18
+
19
+ function formatLog(level, message) {
20
+ const info = levels[level] || levels.info;
21
+ const label = info.label;
22
+ return `[${getTimestamp()}] [${label}] ${message}`;
23
+ }
24
+
25
+ function log(level, message, ...meta) {
26
+ const normalizedLevel = String(level || 'info').toLowerCase();
27
+ if (normalizedLevel === 'debug' && !isDebugEnabled()) {
28
+ return;
29
+ }
30
+
31
+ const info = levels[normalizedLevel] || levels.info;
32
+ const formatted = info.color(formatLog(normalizedLevel, message));
33
+
34
+ if (normalizedLevel === 'error') {
35
+ console.error(formatted, ...meta);
36
+ } else if (normalizedLevel === 'warn') {
37
+ console.warn(formatted, ...meta);
38
+ } else {
39
+ console.log(formatted, ...meta);
40
+ }
41
+ }
42
+
43
+ function logError(error, message = '') {
44
+ const header = message ? `${message} - ` : '';
45
+ const stack = error && error.stack ? error.stack : String(error);
46
+ log('error', `${header}${stack}`);
47
+ }
48
+
49
+ module.exports = {
50
+ log,
51
+ info: (message, ...meta) => log('info', message, ...meta),
52
+ warn: (message, ...meta) => log('warn', message, ...meta),
53
+ error: (message, ...meta) => log('error', message, ...meta),
54
+ debug: (message, ...meta) => log('debug', message, ...meta),
55
+ logError,
56
+ isDebugEnabled,
57
+ };
package/src/timer.js ADDED
@@ -0,0 +1,31 @@
1
+ const timers = new Map();
2
+
3
+ function startTimer(label = 'default') {
4
+ timers.set(label, process.hrtime.bigint());
5
+ }
6
+
7
+ function endTimer(label = 'default', options = {}) {
8
+ const start = timers.get(label);
9
+ if (!start) {
10
+ throw new Error(`Timer '${label}' was not started.`);
11
+ }
12
+
13
+ const durationNs = process.hrtime.bigint() - start;
14
+ timers.delete(label);
15
+ const durationMs = Number(durationNs) / 1e6;
16
+ const message = `${label}: ${durationMs.toFixed(3)} ms`;
17
+
18
+ if (options.log !== false) {
19
+ console.log(message);
20
+ }
21
+
22
+ return {
23
+ label,
24
+ durationMs,
25
+ };
26
+ }
27
+
28
+ module.exports = {
29
+ startTimer,
30
+ endTimer,
31
+ };