Golang captures panic stack information

  • 2020-06-23 00:40:24
  • OfStack

In golang, if there are too many goroutine started in panic, the screen will be full of information. In the terminal tool, there is too much information brushed to find the information in front. Therefore, it is necessary for the program to capture panic and output the error information to the file, so as to locate and check the problem.

Golang captures panic stack information


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 panic information captured directly by recover() Rather than leaving the stack information printed by panic alone, line 1 is the line where panic occurred Simpler than leaving the stack information printed by panic, you can specify the amount of information (kb)

Finally, if you are starting multiple goroutine, you need to write defer PanicHandler() for each goroutine function. Otherwise, you will not be able to capture painc information from other goroutine.

conclusion


Related articles: