0

how to console.log the line number of the called function or console.log()

for example in the IDE i can see the line like this. how can I show that by console.log it

14 
15 // other code/logic
16
17 console.error(`error at line ${herePutTheLogic}`);
18

output: error at line 17

enter image description here

stackdeveloper
  • 352
  • 2
  • 21
  • https://kaihao.dev/posts/console-log-with-line-numbers – kelsny Sep 13 '22 at 15:07
  • Does this answer your question? [A proper wrapper for console.log with correct line number?](https://stackoverflow.com/questions/13815640/a-proper-wrapper-for-console-log-with-correct-line-number) – Ethicist Sep 13 '22 at 15:07
  • If you're coding into VSCode, [Turbo Console Log](https://marketplace.visualstudio.com/items?itemName=ChakrounAnas.turbo-console-log) might be right choice if you don't want to go deep into creating your own solution for it! – Mr.Online Sep 13 '22 at 15:09
  • Similar question https://stackoverflow.com/questions/1340872/how-to-get-javascript-caller-function-line-number-and-caller-source-url – Peterrabbit Sep 13 '22 at 15:09

1 Answers1

3

You can use (new Error()).stack to get the stack trace at the current line. it would require some additional parsing to get the line number however.

e.g., console.log((new Error()).stack.split(':')[1]) will get it assuming it is at the root of the file, but once you start adding it to functions you'd need something a little more sophisticated.

console.log(
  "❌ the error is on the line N." +
  new Error().stack.split(":")[3]
);
Laaouatni Anas
  • 4,199
  • 2
  • 7
  • 26
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65