how to hook into console logs in vue js in order to output them in the webpage?

Viewed 36

I'm trying to build an online code editor. in which i need to print the console logs in the web page when user executes their code.

i've tried:

console.log = function(msg){
   alert('my .log hook received message - '+msg); 
   //add your logic here
}

but it does not seem to work properly. is there any console logs handler package to use?

i'm using VueJS.

1 Answers

console.log takes an indefinite number of arguments and prints each of them into the console.

The replacement you wrote only takes one argument. Which means any subsequent arguments after the first will not be logged.

To log everything, you might want to use:

console.log = function(...args) {
  args.forEach(msg => {
    alert('my .log hook received message - '+msg); 
  })
}

The above overrides printing to console. If you want the console to keep printing and run your code on top, you have to call the original function from the replacement:

const originalLogFn = console.log;
console.log = (...args) => {
  // do your thing with args

  // print to console:
  originalLogFn.apply(console, args) 
}
Related