console.trace()
outputs its result on console.
I want to get the results as string and save them to a file.
I don't define names for functions and I also can not get their names with callee.caller.name
.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
I'm not sure about firefox, but in v8/chrome you can use a method on the Error constructor called
captureStackTrace
. (More info here)So a hacky way to get it would be:
Normally,
getStackTrace
would be on the stack when it's captured. The second argument there excludesgetStackTrace
from being included in the stack trace.This is only a minor enhancement to Konstantin's excellent code. It cuts a bit on the expense of throwing-catching and just instantiates the Error stack:
I usually want a specific level of stack trace (for my custom logger) so this is also possible when calling:
This will give a stack trace (as array of strings) for modern Chrome, Firefox, Opera and IE10+
Usage:
It excludes from the stack its own call as well as title "Error" that is used by Chrome and Firefox (but not IE).
It shouldn't crash on older browsers but just return empty array. If you need more universal solution look at stacktrace.js. Its list of supported browsers is really impressive but to my mind it is very big for that small task it is intended for: 37Kb of minified text including all dependencies.
Error.stack is what you need. It works in Chrome and Firefox. For example
will give in Chrome:
and in Firefox:
There is a library called stacktrace.js that gives you cross browser stack traces. You can use it simply by including the script and calling at any point: