improve logging

This commit is contained in:
Asraelite 2016-03-28 11:13:19 +01:00
parent 9f2cbf2bce
commit ce5f5380e1
2 changed files with 36 additions and 22 deletions

View file

@ -9,6 +9,8 @@ const packageJson = require('../package.json');
class WingbaseServer extends ServerInterface {
constructor() {
super();
process.on('SIGINT', this.stop.bind(this));
}
start() {
@ -18,12 +20,13 @@ class WingbaseServer extends ServerInterface {
this.webServer.start();
this.gameServer.start();
this.log(`Wingbase version ${packageJson.version} running.`);
this.log(`Wingbase version ${packageJson.version} running.`, 'bold');
}
stop() {
this.log('Server stopping.');
process.exit();
this.log('Server stopping.', 'bold');
this.capLogfile();
setTimeout(process.exit, 100);
}
}

View file

@ -2,6 +2,13 @@
const fs = require('fs');
const pad = (str, len, right) => {
str = '' + str;
return (right ? str : '') +
Array(len > str.length ? 1 + len - str.length : 0)
.join('0') + (right ? '' : str);
};
require('colors');
class ServerInterface {
@ -10,30 +17,13 @@ class ServerInterface {
}
log(msg) {
let pad = (str, len, right) => {
str = '' + str;
return (right ? str : '') +
Array(len > str.length ? 1 + len - str.length : 0)
.join('0') + (right ? '' : str);
}
let d = new Date();
let timestamp =
`<${pad(d.getUTCHours(), 2)}:` +
`${pad(d.getUTCMinutes(), 2)}:` +
`${pad(d.getUTCSeconds(), 2)}.` +
`${pad(('' + d.getUTCMilliseconds()).slice(0, 2), 2, true)}> `;
let timestamp = this.timestamp;
let output = msg;
Array.from(arguments).splice(1).forEach(a => output = output[a]);
output = timestamp.gray + output;
// Clear and go to start of line.
console.log('\x1b[2K\x1b[999D' + output);
let date =
`${pad(d.getUTCFullYear(), 2)}-` +
`${pad(d.getUTCMonth(), 2)}-` +
`${pad(d.getUTCDate(), 2)}`;
fs.appendFile('log/' + date + '.log', timestamp + msg + '\n');
fs.appendFile(this.logfile, timestamp + msg + '\n');
}
debug(msg) {
@ -43,6 +33,27 @@ class ServerInterface {
error(msg) {
this.log(msg, 'red');
}
capLogfile() {
fs.appendFile(this.logfile, '-----------\n');
}
get timestamp() {
let d = new Date();
return `<${pad(d.getUTCHours(), 2)}:` +
`${pad(d.getUTCMinutes(), 2)}:` +
`${pad(d.getUTCSeconds(), 2)}.` +
`${pad(('' + d.getUTCMilliseconds()).slice(0, 2), 2, true)}> `;
}
get logfile() {
let d = new Date();
let date =
`${pad(d.getUTCFullYear(), 2)}-` +
`${pad(d.getUTCMonth(), 2)}-` +
`${pad(d.getUTCDate(), 2)}`;
return 'log/' + date + '.log';
}
}
module.exports = ServerInterface;