2

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.

JoshMc
  • 10,239
  • 2
  • 19
  • 38
Aditi Lal
  • 31
  • 2

1 Answers1

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