-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogger_System.gs
More file actions
412 lines (373 loc) · 14.8 KB
/
Copy pathLogger_System.gs
File metadata and controls
412 lines (373 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/**
* @file Logger_System.gs
* @description Sistema centralizado de logging e tratamento de erros do EnSiSanar.
* Roteia mensagens para três destinos conforme nível de severidade:
*
* Nível │ console (Stackdriver) │ Aba SystemLogs │ E-mail admin
* ───────────┼──────────────────────┼────────────────┼──────────────
* DEBUG │ console.log │ │
* INFO │ console.log │ │
* WARN │ console.warn │ ✓ │
* ERROR │ console.error │ ✓ │ ✓ throttled (15 min)
* CRITICAL │ console.error │ ✓ │ ✓ imediato (sem throttle)
*
* Principal entry point: Logger_System.logError(e, context)
* – Aceita qualquer Error object ou string.
* – Extrai mensagem, nome e stack automaticamente.
* – Roteia para Stackdriver + SystemLogs + e-mail ao admin.
*
* Logger_System.logCritical(e, context)
* – Igual ao logError mas classifica como CRITICAL e ignora throttle.
* – Use para falhas que impedem o funcionamento (DB inacessível, etc.).
*
* @module Logger_System
* @namespace Logger_System
* @author EnSiSanar Dev Team
* @version 1.0.0
* @since 2026-04-16
* @requires Config – APP_VERSION, ADMIN_EMAIL via PropertiesService
* @requires DB_Core – getSheet() para aba SystemLogs
* @requires Email_Service – sendAlert() para notificações ao administrador
*/
const Logger_System = {
// ─── CONSTANTES INTERNAS ──────────────────────────────────────────────────
/**
* @private
* Mapa de nível → valor numérico para comparação de severidade.
*/
_LEVELS: { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, CRITICAL: 4 },
/** @private Nível mínimo para persistir na aba SystemLogs (WARN = 2). */
_SHEET_MIN_LEVEL: 2,
/** @private Nível mínimo para disparar e-mail de alerta (ERROR = 3). */
_EMAIL_MIN_LEVEL: 3,
/** @private Chave na ScriptProperty para throttle de e-mail entre alerts. */
_THROTTLE_PROP: 'LOGGER_LAST_EMAIL_MS',
/**
* @private
* Janela de throttle para e-mails de alerta (15 min).
* CRITICAL ignora esta janela e sempre envia.
*/
_THROTTLE_MS: 15 * 60 * 1000,
/** @private Nome da aba de log persistente no Spreadsheet. */
_SHEET_NAME: 'SystemLogs',
/**
* @private
* Cabeçalhos da aba SystemLogs.
* Deve estar em sincronia com DB_Core._SCHEMAS.SystemLogs.
*/
_HEADERS: [
'Timestamp', 'Level', 'Module',
'Message', 'ErrorName', 'ErrorStack', 'Context'
],
// ─── HELPERS PRIVADOS ─────────────────────────────────────────────────────
/**
* @private
* Obtém a aba SystemLogs. DB_Core.getSheet() é idempotente e cria com
* cabeçalhos se necessário (schema definido em DB_Core._SCHEMAS).
* Envolto em try/catch para garantir que logging NUNCA lance exceções.
*
* @returns {GoogleAppsScript.Spreadsheet.Sheet|null}
*/
_getSheet: function () {
try {
return DB_Core.getSheet(Logger_System._SHEET_NAME);
} catch (e) {
console['error']('[Logger_System._getSheet] Não foi possível acessar SystemLogs: ' + e.message);
return null;
}
},
/**
* @private
* Persiste uma entrada de log na aba SystemLogs via appendRow (atômico).
* Chamado apenas para WARN, ERROR e CRITICAL.
*
* @param {Object} entry – objeto de log estruturado
*/
_persistToSheet: function (entry) {
try {
const sheet = Logger_System._getSheet();
if (!sheet) return;
sheet.appendRow([
entry.timestamp,
entry.level,
entry.module,
entry.message,
entry.errorName || '',
entry.errorStack || '',
entry.context || ''
]);
} catch (e) {
// Logging nunca pode lançar — erro aqui seria recursivo
console['error']('[Logger_System._persistToSheet] ' + e.message);
}
},
/**
* @private
* Verifica se o throttle de e-mail está ativo.
* CRITICAL nunca é throttled — sempre envia.
*
* @param {string} level
* @returns {boolean} true = throttle ativo (não enviar)
*/
_isThrottled: function (level) {
if (level === 'CRITICAL') return false;
try {
const raw = PropertiesService.getScriptProperties()
.getProperty(Logger_System._THROTTLE_PROP);
if (!raw) return false;
return (Date.now() - Number(raw)) < Logger_System._THROTTLE_MS;
} catch (e) {
return false; // em caso de falha na prop, permite o envio
}
},
/**
* @private
* Persiste o timestamp do último e-mail enviado (para throttle).
*/
_markEmailSent: function () {
try {
PropertiesService.getScriptProperties()
.setProperty(Logger_System._THROTTLE_PROP, String(Date.now()));
} catch (e) {
console['error']('[Logger_System._markEmailSent] ' + e.message);
}
},
/**
* @private
* Envia e-mail de alerta ao administrador via Email_Service.
* Respeita janela de throttle de 15 min (exceto CRITICAL).
* Silencia erros de envio para não mascarar o erro original.
*
* @param {Object} entry – objeto de log estruturado
*/
_sendEmailAlert: function (entry) {
try {
const adminEmail = Config.ADMIN_EMAIL;
if (!adminEmail) return; // sem destinatário configurado
if (Logger_System._isThrottled(entry.level)) {
console['warn']('[Logger_System] Alerta throttled – último e-mail < 15 min atrás.');
return;
}
const subject = '[EnSiSanar ' + entry.level + '] ' +
entry.module + ': ' +
entry.message.substring(0, 80);
const lines = [
'=== EnSiSanar – Alerta de Sistema ===',
'',
'Nível: ' + entry.level,
'Módulo: ' + entry.module,
'Data: ' + entry.timestamp.toISOString(),
'Versão: ' + Config.APP_VERSION,
'',
'─── Mensagem ─────────────────────────',
entry.message,
''
];
if (entry.errorName) lines.push('Tipo: ' + entry.errorName);
if (entry.context) lines.push('Ctx: ' + entry.context);
if (entry.errorStack) {
lines.push('', '─── Stack Trace ──────────────────────', entry.errorStack);
}
lines.push('', '─────────────────────────────────────',
'Acesse o Stackdriver para detalhes completos:',
'https://console.cloud.google.com/logs');
Email_Service.sendAlert(adminEmail, subject, lines.join('\n'));
Logger_System._markEmailSent();
} catch (e) {
console['error']('[Logger_System._sendEmailAlert] Falha ao enviar alerta: ' + e.message);
}
},
/**
* @private
* Núcleo de roteamento: compõe a entrada de log e distribui aos destinos.
*
* @param {string} level – 'DEBUG'|'INFO'|'WARN'|'ERROR'|'CRITICAL'
* @param {string} message – texto da mensagem
* @param {string} module – módulo/contexto (ex: 'Auth.login')
* @param {Error|null} error – objeto Error, se aplicável
*/
_write: function (level, message, module, error) {
const levelNum = Logger_System._LEVELS[level] !== undefined
? Logger_System._LEVELS[level] : 0;
const entry = {
timestamp: new Date(),
level: level,
module: module || 'System',
message: String(message),
errorName: error ? (error.name || 'Error') : '',
errorStack: error ? (error.stack || '') : '',
context: module || ''
};
// ── Destino 1: Google Cloud Logging via console ────────────────────────
const tag = '[' + level + '][' + entry.module + '] ';
if (levelNum >= Logger_System._LEVELS.ERROR) {
console['error'](tag + entry.message +
(entry.errorStack ? '\n' + entry.errorStack : ''));
} else if (levelNum >= Logger_System._LEVELS.WARN) {
console['warn'](tag + entry.message);
} else {
console['log'](tag + entry.message);
}
// ── Destino 2: Aba SystemLogs (WARN+) ─────────────────────────────────
if (levelNum >= Logger_System._SHEET_MIN_LEVEL) {
Logger_System._persistToSheet(entry);
}
// ── Destino 3: E-mail de alerta ao admin (ERROR+) ─────────────────────
if (levelNum >= Logger_System._EMAIL_MIN_LEVEL) {
Logger_System._sendEmailAlert(entry);
}
},
// ─── API PÚBLICA: MÉTODOS DE LOG POR NÍVEL ────────────────────────────────
/**
* Mensagem de depuração — apenas Stackdriver. Use durante desenvolvimento.
* @public
* @param {string} message
* @param {string} [module] – ex: 'EEG_Processor.calcBands'
*/
debug: function (message, module) {
Logger_System._write('DEBUG', message, module, null);
},
/**
* Evento informativo — apenas Stackdriver. Use para operações normais.
* @public
* @param {string} message
* @param {string} [module]
*/
info: function (message, module) {
Logger_System._write('INFO', message, module, null);
},
/**
* Aviso — Stackdriver + SystemLogs. Situações anómalas mas não críticas.
* @public
* @param {string} message
* @param {string} [module]
*/
warn: function (message, module) {
Logger_System._write('WARN', message, module, null);
},
/**
* Erro — Stackdriver + SystemLogs + e-mail (throttled 15 min).
* @public
* @param {string} message
* @param {string} [module]
*/
error: function (message, module) {
Logger_System._write('ERROR', message, module, null);
},
/**
* Falha crítica — Stackdriver + SystemLogs + e-mail imediato (sem throttle).
* Use quando o sistema não consegue funcionar: DB inacessível, credenciais
* inválidas, perda de dados.
* @public
* @param {string} message
* @param {string} [module]
*/
critical: function (message, module) {
Logger_System._write('CRITICAL', message, module, null);
},
// ─── API PÚBLICA: WRAPPERS DE EXCEÇÃO ─────────────────────────────────────
/**
* Wrapper principal para tratamento de exceções capturadas em blocos catch.
* Extrai mensagem, nome e stack do Error automaticamente e classifica como ERROR.
* Roteia para Stackdriver + SystemLogs + e-mail (throttled).
*
* @public
* @param {Error|string} e – exceção capturada
* @param {string} context – onde ocorreu: ex. 'Patient_CRUD.create'
*
* @example
* try {
* DB_Core.insert('Patients', data);
* } catch (e) {
* Logger_System.logError(e, 'Patient_CRUD.create');
* return { success: false, message: 'Erro interno.' };
* }
*/
logError: function (e, context) {
const isError = e && (e instanceof Error || typeof e.message !== 'undefined');
Logger_System._write(
'ERROR',
isError ? e.message : String(e),
context || 'Unknown',
isError ? e : null
);
},
/**
* Wrapper para falhas críticas que exigem resposta imediata.
* Classifica como CRITICAL — e-mail enviado sem throttle.
*
* @public
* @param {Error|string} e
* @param {string} context
*
* @example
* // Em Backup_Service após falha total:
* Logger_System.logCritical(e, 'Backup_Service.run');
*/
logCritical: function (e, context) {
const isError = e && (e instanceof Error || typeof e.message !== 'undefined');
Logger_System._write(
'CRITICAL',
isError ? e.message : String(e),
context || 'Unknown',
isError ? e : null
);
},
// ─── API PÚBLICA: DIAGNÓSTICO ─────────────────────────────────────────────
/**
* Retorna as últimas N entradas de log da aba SystemLogs.
* Leitura em lote — uma única chamada à API do Sheets.
* Útil para painéis de diagnóstico no dashboard de admin.
*
* @public
* @param {number} [limit=50] – máximo de entradas a retornar
* @returns {Object[]} entradas do mais recente ao mais antigo
*
* @example
* const logs = Logger_System.getRecentLogs(20);
*/
getRecentLogs: function (limit) {
try {
const sheet = Logger_System._getSheet();
if (!sheet || sheet.getLastRow() <= 1) return [];
const n = Math.min(limit || 50, sheet.getLastRow() - 1);
const startRow = Math.max(2, sheet.getLastRow() - n + 1);
const rows = sheet
.getRange(startRow, 1, n, Logger_System._HEADERS.length)
.getValues(); // ← leitura em lote
return rows.reverse().map(function (row) {
return Logger_System._HEADERS.reduce(function (obj, h, i) {
obj[h] = row[i];
return obj;
}, {});
});
} catch (e) {
console['error']('[Logger_System.getRecentLogs] ' + e.message);
return [];
}
},
/**
* Conta entradas por nível nas últimas 24 horas.
* Útil para widgets de saúde do sistema no dashboard.
*
* @public
* @returns {{ DEBUG: number, INFO: number, WARN: number,
* ERROR: number, CRITICAL: number }}
*/
getSummary24h: function () {
const counts = { DEBUG: 0, INFO: 0, WARN: 0, ERROR: 0, CRITICAL: 0 };
try {
const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000);
const logs = Logger_System.getRecentLogs(200);
logs.forEach(function (entry) {
const ts = entry['Timestamp'];
if (ts && new Date(ts) >= cutoff && counts[entry['Level']] !== undefined) {
counts[entry['Level']]++;
}
});
} catch (e) {
console['error']('[Logger_System.getSummary24h] ' + e.message);
}
return counts;
}
}; // ── fim do namespace Logger_System ──────────────────────────────────────────