Commit 770e60ff authored by Michael Henretty's avatar Michael Henretty

make all console operations output json, closes #308

parent 38fce5b1
const os = require('os');
const NAME = 'voice';
const LEVEL_LOG = 'log';
const LEVEL_ERROR = 'error';
interface MessageFields {
name: string;
level: string;
hostname: string;
pid: number;
msg: string;
time: string;
}
export default class Logger {
name: string;
hostname: string;
pid: number;
boundLog: Function;
boundError: Function;
constructor() {
this.name = NAME;
this.hostname = os.hostname();
this.pid = process.pid;
this.boundLog = null;
this.boundError = null;
}
private getDateString() {
return new Date().toISOString()
}
private getMessageFields(level: string, msg: string): MessageFields {
return {
name: this.name,
level: level,
hostname: this.hostname,
pid: this.pid,
msg: msg,
time: this.getDateString()
};
}
private printFields(fields: MessageFields) {
if (!this.boundLog) {
console.error('unable to print without overriding console');
return;
}
let output = JSON.stringify(fields);
if (fields.level === LEVEL_LOG) {
this.boundLog(output);
} else if (fields.level === LEVEL_ERROR) {
this.boundError(output);
}
}
log(...args) {
this.printFields(this.getMessageFields(LEVEL_LOG, args.join(', ')));
}
error(...args) {
this.printFields(this.getMessageFields(LEVEL_ERROR, args.join(', ')));
}
overrideConsole() {
if (this.boundLog) {
this.error('already overrode console');
return;
}
// Override console.log to user our json logger.
this.boundLog = console.log.bind(console);
console.log = (...args) => {
this.log(...args);
}
// Override console.error to user our json logger.
this.boundError = console.error.bind(console);
console.error = (...args) => {
this.error(...args);
}
}
}
import * as http from 'http';
import API from './lib/api';
import Clip from './lib/clip';
import Logger from './lib/logger';
const DEFAULT_PORT = 9000;
const CONFIG_PATH = '../../config.json';
......@@ -12,6 +13,7 @@ const config = require(CONFIG_PATH);
export default class Server {
api: API;
clip: Clip;
logger: Logger;
staticServer: any;
constructor() {
......@@ -19,6 +21,10 @@ export default class Server {
this.staticServer = new nodeStatic.Server(CLIENT_PATH, { cache: false });
this.api = new API();
this.clip = new Clip();
// JSON format all console operations.
this.logger = new Logger();
this.logger.overrideConsole();
}
/**
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment