forked from smogon/pokemon-showdown
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrashlogger.js
96 lines (82 loc) · 2.37 KB
/
crashlogger.js
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
/**
* Crash logger
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Logs crashes, sends an e-mail notification if you've set up
* config.js to do that.
*
* @license MIT license
*/
'use strict';
const fs = require('fs');
const path = require('path');
const CRASH_EMAIL_THROTTLE = 5 * 60 * 1000; // 5 minutes
const LOCKDOWN_PERIOD = 30 * 60 * 1000; // 30 minutes
const logPath = path.resolve(__dirname, 'logs/errors.txt');
let lastCrashLog = 0;
/** @type {any} */
let transport;
/**
* Logs when a crash happens to console, then e-mails those who are configured
* to receive them.
*
* @param {Error} err
* @param {string} description
* @param {?Object} [data = null]
* @return {?string}
*/
module.exports = function crashlogger(err, description, data = null) {
const datenow = Date.now();
let stack = (err.stack || err);
if (data) {
stack += `\n\nAdditional information:\n`;
for (let k in data) {
stack += ` ${k} = ${data[k]}\n`;
}
}
console.error(`\nCRASH: ${stack}\n`);
let out = fs.createWriteStream(logPath, {'flags': 'a'});
out.on('open', () => {
out.write(`\n${stack}\n`);
out.end();
}).on('error', /** @param {Error} err */ err => {
console.error(`\nSUBCRASH: ${err.stack}\n`);
});
if (Config.crashguardemail && ((datenow - lastCrashLog) > CRASH_EMAIL_THROTTLE)) {
lastCrashLog = datenow;
if (!transport) {
try {
require.resolve('nodemailer');
} catch (e) {
throw new Error(
'nodemailer is not installed, but it is required if Config.crashguardemail is configured! ' +
'Run npm install --no-save nodemailer and restart the server.'
);
}
}
let text = `${description} crashed `;
if (transport) {
text += `again with this stack trace:\n${stack}`;
} else {
try {
transport = require('nodemailer').createTransport(Config.crashguardemail.options);
} catch (e) {
throw new Error("Failed to start nodemailer; are you sure you've configured Config.crashguardemail correctly?");
}
text += `with this stack trace:\n${stack}`;
}
transport.sendMail({
from: Config.crashguardemail.from,
to: Config.crashguardemail.to,
subject: Config.crashguardemail.subject,
text,
}, /** @param {?Error} err */ err => {
if (err) console.error(`Error sending email: ${err}`);
});
}
if (process.uptime() * 1000 < LOCKDOWN_PERIOD) {
// lock down the server
return 'lockdown';
}
return null;
};