When panic is started in golang, if there are more goroutines and the information is flashed on the screen, the information on the terminal tool cannot be found, so it is necessary for the program to capture the panic by itself and output the error information to the file in order to locate and troubleshoot the problem.
Golang captures panic stack information
func PanicTrace(kb int) []byte { s := []byte("/src/runtime/") e := []byte("\ngoroutine ") line := []byte("\n") stack := make([]byte, kb<<10) //4KB length := (stack, true) start := (stack, s) stack = stack[start:length] start = (stack, line) + 1 stack = stack[start:] end := (stack, line) if end != -1 { stack = stack[:end] } end = (stack, e) if end != -1 { stack = stack[:end] } stack = (stack, "\n") return stack }
Advantages of this function:
- More detailed than the panic information captured directly by recover()
- More accurate than just letting the stack information printed by panic, the first line is the code line where panic occurs
- It is simpler than just letting the stack information printed by its panic, and you can specify the amount of information (kb)
Finally, note that if you start multiple goroutines, you need to write defer PanicHandler() when each goroutine executes the function. Otherwise, the painc information in other goroutines will not be captured.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links