My react application is deployed on pcf. I want to get logs there. console.log print logs to browser. I want it in terminal, similar to backend services. Can anyone help me on this.
Asked
Active
Viewed 2,178 times
1 Answers
1
You can try to start a new service using WebSocket. Start it when your project start.
const WebSocket = require('ws');
const chalk = require('chalk');
const { log } = console;
const logParse = (data) => {
return data.map((it) => JSON.stringify(it)).join(' ');
};
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
const event = JSON.parse(message);
const { type, data } = event;
switch (type) {
case 'log':
log('>>', logParse(data));
break;
case 'error':
log('>>', chalk.red(logParse(data)));
break;
case 'warn':
log('>>', chalk.yellow(logParse(data)));
break;
case 'debug':
log('>>', chalk.blue(logParse(data)));
break;
default:
log('>>', logParse(data));
}
});
ws.send('something');
});
And then, rewrite your local console.log
to send the logs to the service.
const exampleSocket = new WebSocket(`ws://${window.location.hostname}:8080`);
exampleSocket.onopen = function (e) {
console.log('ws connected');
};
console.stdlog = console.log.bind(console);
console.log = function () {
exampleSocket.send(
JSON.stringify({ type: 'log', data: Array.from(arguments) })
);
console.stdlog.apply(console, arguments);
};
console.error = function () {
exampleSocket.send(
JSON.stringify({ type: 'error', data: Array.from(arguments) })
);
console.stdlog.apply(console, arguments);
};
console.defaultWarn = console.warn.bind(console);
console.warn = function () {
exampleSocket.send(
JSON.stringify({ type: 'warn', data: Array.from(arguments) })
);
console.defaultWarn.apply(console, arguments);
};
console.defaultDebug = console.debug.bind(console);
console.debug = function () {
exampleSocket.send(
JSON.stringify({ type: 'debug', data: Array.from(arguments) })
);
console.defaultDebug.apply(console, arguments);
};

Angelki
- 103
- 8
-
So it's just like sending logs to server? – Aditi Lal Jan 22 '21 at 02:59
-
Yes, and if you use the phone to debug web pages locally, the relevant logs will also be displayed on the terminal. – Angelki Jan 22 '21 at 03:05
-
1Great solution and I was able to integrate this into my project in only 10 minutes. Thanks! – Badr B Dec 29 '22 at 04:30