add show options and change mechanism to unpack messsage

This commit is contained in:
Earther 2021-08-27 17:19:05 +07:00
parent d21680a5f9
commit 51d17d40a3
5 changed files with 91 additions and 54 deletions

View File

@ -39,9 +39,13 @@ __Note__: with this approach you have to do all steps 3-6 every-time you refresh
## Advanced options
With `tconsole` command:
- `--out path`: save log to file
- `--out path`: Save log to file
- `--port port`: Change server port
- `--addr addr`: Change server address
- `--show levels`: Select log levels to display (info | warning | error | debug). Multiple levels are seperated by `,`
> use `.show levels` while the server running to select again
With `tconsole` package:

View File

@ -7,22 +7,22 @@ const configure = (conn, defaultConsole) => {
console._tsconsole_configured = true;
console.log = (...args) => {
sendWhenConnected(conn, JSON.stringify({ type: 'log', data: Array.from(args) }));
sendWhenConnected(conn, JSON.stringify({ type: 'log', data: Array.from(args) , }), defaultConsole);
defaultConsole.log.apply(defaultConsole, args);
};
console.error = (...args) => {
sendWhenConnected(conn, JSON.stringify({ type: 'error', data: Array.from(args) }));
sendWhenConnected(conn, JSON.stringify({ type: 'error', data: Array.from(args) }), defaultConsole);
defaultConsole.error.apply(defaultConsole, args);
};
console.warn = (...args) => {
sendWhenConnected(conn, JSON.stringify({ type: 'warn', data: Array.from(args) }));
sendWhenConnected(conn, JSON.stringify({ type: 'warn', data: Array.from(args) }), defaultConsole);
defaultConsole.warn.apply(defaultConsole, args);
};
console.debug = (...args) => {
sendWhenConnected(conn, JSON.stringify({ type: 'debug', data: Array.from(args) }));
sendWhenConnected(conn, JSON.stringify({ type: 'debug', data: Array.from(args) }), defaultConsole);
defaultConsole.debug.apply(defaultConsole, args);
};
@ -31,7 +31,6 @@ const configure = (conn, defaultConsole) => {
const release = (defaultConsole) => {
console = defaultConsole;
console._tsconsole_configured = false;
ws = null;
}
const termlog = (options = {}) => {
@ -67,7 +66,7 @@ const termlog = (options = {}) => {
// *** Utils *** //
const sendWhenConnected = (ws, msg, n = 0, maxTries = 100) => {
const sendWhenConnected = (ws, msg, defaultConsole, n = 0, maxTries = 100) => {
// Closing or closed
if (ws.readyState === 2 || ws.readyState === 3) return;
@ -76,9 +75,9 @@ const sendWhenConnected = (ws, msg, n = 0, maxTries = 100) => {
if (ws.readyState === 1) {
ws.send(msg);
} else if (n < maxTries) {
sendWhenConnected(ws, msg, n + 1);
sendWhenConnected(ws, msg, defaultConsole, n + 1);
} else{
console.error("Exceed tries to send message: ", msg);
defaultConsole.error("Exceed tries to send message: ", msg);
}
}, 10); // wait 10 milisecond for the connection...
}

10
package-lock.json generated
View File

@ -1,21 +1,20 @@
{
"name": "termsole",
"name": "termlog",
"version": "1.0.0",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "termsole",
"name": "termlog",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"chalk": "^4.1.2",
"minimist": "^1.2.5",
"repl": "^0.1.3",
"ws": "^8.2.0"
},
"bin": {
"tconsole": "cli.js"
"tconsole": "server.js"
}
},
"node_modules/ansi-styles": {
@ -126,8 +125,7 @@
}
},
"chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"version": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"requires": {
"ansi-styles": "^4.1.0",

View File

@ -1,6 +1,6 @@
{
"name": "termlog",
"version": "1.0.0",
"version": "1.1.0",
"description": "Console log to terminal",
"type": "main",
"scripts": {
@ -22,7 +22,6 @@
},
"homepage": "https://github.com/qnkhuat/termlog#readme",
"dependencies": {
"chalk": "^4.1.2",
"minimist": "^1.2.5",
"repl": "^0.1.3",
"ws": "^8.2.0"

109
server.js
View File

@ -1,12 +1,24 @@
#!/usr/bin/env node
const WebSocket = require('ws');
const minimist = require("minimist");
const chalk = require('chalk');
const repl = require('repl');
const DEFAULT_HOST = "localhost";
const DEFAULT_PORT = 3456;
const CRed = "\x1b[31m";
const CYellow = "\x1b[33m";
const CWhite = "\x1b[37m";
const CBlue = "\x1b[34m";
const LOGLEVELS = ['log', 'warn', 'error', 'debug'];
// global var keeping track of what to display
let SHOWLEVELS = LOGLEVELS;
function heartbeat() {
this.isAlive = true;
}
const getTime = () => {
const now = new Date();
const hours = (now.getHours() > 9 ? "" : "0") + now.getHours();
@ -15,43 +27,42 @@ const getTime = () => {
return `[${hours}:${minutes}:${seconds}]`;
}
const out = (text, color = "white", stream = null) => {
switch (color) {
case "white":
text = `${getTime()} ${chalk.white(text)}`;
break;
case "red":
text = `${getTime()} ${chalk.red(text)}`;
break;
case "yellow":
text = `${getTime()} ${chalk.yellow(text)}`;
break;
case "blue":
text = `${getTime()} ${chalk.blue(text)}`;
break;
default:
text = `${getTime()} ${chalk.white(text)}`;
break;
}
console.log(text);
if (stream) stream.write(text + "\n");
const out = (data, color = CWhite) => {
process.stdout.write(color);
process.stdout.write(getTime() + " ");
console.log.apply(console, data);
process.stdout.write(CWhite);
}
function heartbeat() {
this.isAlive = true;
const applyShowFilter = (args) => {
let newShowLevels = [];
for (let level of args) {
level = level.trim();
if (LOGLEVELS.includes(level)) newShowLevels.push(level);
else {
console.error("[TERMLOG] Invalid level: ", level);
return false;
}
}
console.log(`[TERMLOG] Show ${newShowLevels.join(",")} only`)
SHOWLEVELS = newShowLevels;
return true;
}
const startServer = (options) => {
console.log(`Server running at: ${options.host}:${options.port}`);
console.log(`[TERMLOG] Server running at: ${options.host}:${options.port}`);
let fileStream;
if (options.out) {
const fs = require('fs');
fileStream = fs.createWriteStream(options.out, {flags: 'a'});
console.log(`Saving log to ${options.out}`);
console.log(`[TERMLOG] Saving log to ${options.out}`);
}
if (options.show) applyShowFilter(options.show);
const server = new WebSocket.Server({ port: options.port, host: options.host});
server.on("connection", (conn) => {
conn.isAlive = true;
@ -60,27 +71,40 @@ const startServer = (options) => {
conn.on('message', (message) => {
const event = JSON.parse(message);
const { type, data } = event;
let { type, data } = event;
if (!Array.isArray(data)) data = [data];
if (!SHOWLEVELS.includes(type)) return;
switch (type) {
case 'log':
data.forEach((text) => out(text, "white", fileStream));
out(data, CWhite);
break;
case 'error':
data.forEach((text) => out(text, "red", fileStream));
out(data, CRed);
break;
case 'warn':
data.forEach((text) => out(text, "yellow", fileStream));
out(data, CYellow);
break;
case 'debug':
data.forEach((text) => out(text, "blue", fileStream));
out(data, CBlue);
break;
default:
data.forEach((text) => out(text, "white"), fileStream);
out(data, CWhite);
break;
}
if (options.out) {
fileStream.write(data.join(" "));
fileStream.write("\n");
}
});
conn.on("close", () => {
out("[TERMLOG]: Closed", conn);
out("[TERMLOG]: Closed", CWhite);
});
});
@ -91,7 +115,6 @@ const startServer = (options) => {
process.exit(status)
}
const interval = setInterval(() => {
server.clients.forEach((conn) => {
if (conn.isAlive === false) return conn.terminate();
@ -107,13 +130,20 @@ const startServer = (options) => {
});
server.on("error", (event) => {
out(event, "red");
out(event, CRed);
closeHandler(1);
})
// Start a node repl
const r = repl.start('> ');
const r = repl.start({prompt: "> "});
r.defineCommand('show', {
help: '[TERMLOG] Select log levels to display (info | warning | error | debug). Multiple levels are seperated by `,`',
action(arg) {
const args = arg.split(",");
applyShowFilter(args);
}
});
r.on('exit', () => {
closeHandler(0);
});
@ -141,11 +171,18 @@ Options:
--out arg
Save output to file
--show args
Select log levels to display (info | warning | error | debug). Multiple levels are seperated by \`,\`
`);
} else {
if (args.show) args.show = args.show.split(",");
const options = {
port: DEFAULT_PORT,
host:DEFAULT_HOST,
show: LOGLEVELS,
...args
}