0

i want to write console logs into logs.json file and saves it like:

{
  "1":"consolelog1",
  "2":"consolelog2",
  "3":"consolelog3"
}
MrEnoX
  • 1
  • 3
  • You can redirect stdout to a file on the command line to capture it and then write a simple script that will process lines of text from the log file into this structure and then write that to `logs.json`. JSON itself is not really a streaming format so probably better to turned it into JSON after all the text output has been captured. – jfriend00 Sep 02 '22 at 17:14
  • Better to not write it as "a single json" file, but write a log file with one json object per line. That way you can load only part of it (i.e. you can "tail" the log) and log visualizer tools will know how to make it easy to work with. – Mike 'Pomax' Kamermans Sep 02 '22 at 17:18

1 Answers1

0

Using node.js, you can use fs:

const fs = require('fs');

function log_to_file(mystuff){
  // GET file
  const file = JSON.parse(fs.readFileSync('./logs.json'));
  // Find number of console.logs already there
  let lognumb = -1, cont = true;
  while(cont){
    if(!(file[lognumb+1]===undefined)){
      lognumb++;
      continue
    };
    cont=false
  };
  file[lognumb+1] = "consolelog"+mystuff;
  fs.writeFileSync("./logs.json",JSON.stringify(file));
}

Then, you can use log_to_file("your_console_log_data") to save your data.

Make Sure You Are Using NODE.JS, Not JAVASCRIPT

Jake
  • 97
  • 1
  • 9