stack.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package fserr
  2. import (
  3. "fmt"
  4. "io"
  5. "path"
  6. "runtime"
  7. "strconv"
  8. "strings"
  9. )
  10. // 借助 pkg error 的堆栈实现
  11. // stack represents a stack of program counters.
  12. type stack []uintptr
  13. func (s *stack) Format(st fmt.State, verb rune) {
  14. switch verb {
  15. case 'v':
  16. switch {
  17. case st.Flag('+'):
  18. for _, pc := range *s {
  19. fmt.Fprintf(st, "\n%+v", frame(pc))
  20. }
  21. }
  22. }
  23. }
  24. func (s *stack) StackTrace() stackTrace {
  25. f := make([]frame, len(*s))
  26. for i := 0; i < len(f); i++ {
  27. f[i] = frame((*s)[i])
  28. }
  29. return f
  30. }
  31. func callers() *stack {
  32. var pcs [32]uintptr
  33. var st stack = pcs[0:runtime.Callers(3, pcs[:])]
  34. return &st
  35. }
  36. // frame represents a program counter inside a stack frame.
  37. // For historical reasons if frame is interpreted as a uintptr
  38. // its value represents the program counter + 1.
  39. type frame uintptr
  40. // pc returns the program counter for this frame;
  41. // multiple frames may have the same PC value.
  42. func (f frame) pc() uintptr { return uintptr(f) - 1 }
  43. // file returns the full path to the file that contains the
  44. // function for this frame's pc.
  45. func (f frame) file() string {
  46. fn := runtime.FuncForPC(f.pc())
  47. if fn == nil {
  48. return "unknown"
  49. }
  50. file, _ := fn.FileLine(f.pc())
  51. return file
  52. }
  53. // line returns the line number of source code of the
  54. // function for this frame's pc.
  55. func (f frame) line() int {
  56. fn := runtime.FuncForPC(f.pc())
  57. if fn == nil {
  58. return 0
  59. }
  60. _, line := fn.FileLine(f.pc())
  61. return line
  62. }
  63. // name returns the name of this function, if known.
  64. func (f frame) name() string {
  65. fn := runtime.FuncForPC(f.pc())
  66. if fn == nil {
  67. return "unknown"
  68. }
  69. return fn.Name()
  70. }
  71. // Format formats the frame according to the fmt.Formatter interface.
  72. //
  73. // %s source file
  74. // %d source line
  75. // %n function name
  76. // %v equivalent to %s:%d
  77. //
  78. // Format accepts flags that alter the printing of some verbs, as follows:
  79. //
  80. // %+s function name and path of source file relative to the compile time
  81. // GOPATH separated by \n\t (<funcname>\n\t<path>)
  82. // %+v equivalent to %+s:%d
  83. func (f frame) Format(s fmt.State, verb rune) {
  84. switch verb {
  85. case 's':
  86. switch {
  87. case s.Flag('+'):
  88. io.WriteString(s, f.name())
  89. io.WriteString(s, "\n\t")
  90. io.WriteString(s, f.file())
  91. default:
  92. io.WriteString(s, path.Base(f.file()))
  93. }
  94. case 'd':
  95. io.WriteString(s, strconv.Itoa(f.line()))
  96. case 'n':
  97. io.WriteString(s, funcname(f.name()))
  98. case 'v':
  99. f.Format(s, 's')
  100. io.WriteString(s, ":")
  101. f.Format(s, 'd')
  102. }
  103. }
  104. // MarshalText formats a stacktrace frame as a text string. The output is the
  105. // same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
  106. func (f frame) MarshalText() ([]byte, error) {
  107. name := f.name()
  108. if name == "unknown" {
  109. return []byte(name), nil
  110. }
  111. return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
  112. }
  113. // stackTrace is stack of Frames from innermost (newest) to outermost (oldest).
  114. type stackTrace []frame
  115. // Format formats the stack of Frames according to the fmt.Formatter interface.
  116. //
  117. // %s lists source files for each frame in the stack
  118. // %v lists the source file and line number for each frame in the stack
  119. //
  120. // Format accepts flags that alter the printing of some verbs, as follows:
  121. //
  122. // %+v Prints filename, function, and line number for each frame in the stack.
  123. func (st stackTrace) Format(s fmt.State, verb rune) {
  124. switch verb {
  125. case 'v':
  126. switch {
  127. case s.Flag('+'):
  128. for _, f := range st {
  129. io.WriteString(s, "\n")
  130. f.Format(s, verb)
  131. }
  132. case s.Flag('#'):
  133. fmt.Fprintf(s, "%#v", []frame(st))
  134. default:
  135. st.formatSlice(s, verb)
  136. }
  137. case 's':
  138. st.formatSlice(s, verb)
  139. }
  140. }
  141. // formatSlice will format this stackTrace into the given buffer as a slice of
  142. // frame, only valid when called with '%s' or '%v'.
  143. func (st stackTrace) formatSlice(s fmt.State, verb rune) {
  144. io.WriteString(s, "[")
  145. for i, f := range st {
  146. if i > 0 {
  147. io.WriteString(s, " ")
  148. }
  149. f.Format(s, verb)
  150. }
  151. io.WriteString(s, "]")
  152. }
  153. // funcname removes the path prefix component of a function's name reported by func.Name().
  154. func funcname(name string) string {
  155. i := strings.LastIndex(name, "/")
  156. name = name[i+1:]
  157. i = strings.Index(name, ".")
  158. return name[i+1:]
  159. }