This is a created article in which the information may have evolved or changed.
// PanicTrace trace panic stack info.func PanicTrace(kb int) []byte { s := []byte("/src/runtime/panic.go") e := []byte("\ngoroutine ") line := []byte("\n") stack := make([]byte, kb<<10) //4KB length := runtime.Stack(stack, true) start := bytes.Index(stack, s) stack = stack[start:length] start = bytes.Index(stack, line) + 1 stack = stack[start:] end := bytes.LastIndex(stack, line) if end != -1 { stack = stack[:end] } end = bytes.Index(stack, e) if end != -1 { stack = stack[:end] } stack = bytes.TrimRight(stack, "\n") return stack}
Advantages of this function:
- More detailed than the panic information captured by direct recover ()
- is more accurate than letting its panic print stack information, the first line is the line of code that occurs panic
- More concise than the stack information that allows it to be panic printed, you can specify information in kilobytes (KB)