-
Notifications
You must be signed in to change notification settings - Fork 0
/
log-code-stack.go
executable file
·134 lines (112 loc) · 2.32 KB
/
log-code-stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package v_log
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
/* ============================================
Created by andy pangaribuan on 2020/04/01
Copyright BoltIdea. All rights reserved.
============================================ */
func codeStack(err error) string {
if err == nil {
return ""
}
exceptions := []string{
"/github.com/labstack/echo/",
"/libexec/src/net/http/",
}
isOnExceptions := func(filePath string) (isOnEx bool) {
for _, ex := range exceptions {
if strings.Contains(filePath, ex) {
isOnEx = true
break
}
}
return
}
msg := fmt.Sprintf("%+v", err)
arr := strings.Split(msg, "\n")
files := make([][]string, 0)
for _, v := range arr {
if len(v) > 8 && v[:8] == "runtime." {
break
}
if len(v) > 1 && v[:1] == "\t" {
v = v[1:]
vs := strings.Split(v, ":")
if len(vs) == 2 {
if _, err := strconv.Atoi(vs[1]); err == nil {
if !isOnExceptions(vs[0]) {
if _, err := os.Stat(vs[0]); !os.IsNotExist(err) {
files = append(files, vs)
}
}
}
}
}
}
if len(files) > 0 {
codeStack := ""
for _, vs := range files {
lineAt, _ := strconv.Atoi(vs[1])
if codes := readFile(vs[0], lineAt); codes != "" {
if codeStack == "" {
codeStack = ":: START CODE STACK\n\n"
} else {
codeStack += "\n\n\n"
}
codeStack += vs[0] + ":" + vs[1] + "\n"
codeStack += codes
}
}
if codeStack != "" {
codeStack += "\n\n:: END CODE STACK"
return codeStack
}
}
return ""
}
func readFile(filePath string, lineAt int) string {
includeTopLine := 4
includeBottomLine := 4
startAt := lineAt - includeTopLine
stopAt := lineAt + includeBottomLine
file, err := os.Open(filePath)
if err != nil {
return ""
}
scanner := bufio.NewScanner(file)
lineNumber := 0
canStart := false
lines := make([]string, 0)
for scanner.Scan() {
lineNumber++
if canStart {
if lineNumber > stopAt {
break
}
line := scanner.Text()
lines = append(lines, strconv.Itoa(lineNumber) + ": " + line)
} else {
if lineNumber == startAt {
canStart = true
line := scanner.Text()
lines = append(lines, strconv.Itoa(lineNumber) + ": " + line)
}
}
}
n := len(lines)
codes := ""
if n > 0 {
for i, v := range lines {
codes += v
if i + 1 != n {
codes += "\n"
}
}
}
return codes
}