-
Notifications
You must be signed in to change notification settings - Fork 14
/
error_logger.go
177 lines (153 loc) · 3.99 KB
/
error_logger.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package errorlogger
import (
"bytes"
"io/ioutil"
"math"
"net/http/httputil"
"github.com/coretrix/hitrix/service/component/slack"
slackgo "github.com/slack-go/slack"
"github.com/coretrix/hitrix/service/component/app"
//nolint
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"runtime"
"time"
"github.com/gin-gonic/gin"
"github.com/latolukasz/beeorm"
)
const GroupError = "error"
var (
dunno = []byte("???")
centerDot = []byte("·")
dot = []byte(".")
slash = []byte("/")
)
type ErrorLogger interface {
LogErrorWithRequest(c *gin.Context, errData interface{})
LogError(dataFromRecover interface{})
log(errData interface{}, request *http.Request)
}
type ErrorMessage struct {
File string
Line int
AppName string
Request []byte
Message string
Stack []byte
}
type RedisErrorLogger struct {
redisStorage *beeorm.RedisCache
slackService slack.Slack
appService *app.App
}
func NewRedisErrorLogger(appService *app.App, ormService *beeorm.Engine, slackService slack.Slack) ErrorLogger {
return &RedisErrorLogger{redisStorage: ormService.GetRedis(), slackService: slackService, appService: appService}
}
func (e *RedisErrorLogger) LogError(errData interface{}) {
e.log(errData, nil)
}
func (e *RedisErrorLogger) LogErrorWithRequest(c *gin.Context, errData interface{}) {
e.log(errData, c.Request)
}
func (e *RedisErrorLogger) log(errData interface{}, request *http.Request) {
var msg string
err, ok := errData.(error)
if ok {
msg = err.Error()
} else {
msg = errData.(string)
}
logger := log.New(os.Stderr, "\n\n\x1b[31m", log.LstdFlags)
stack := stack(0)
logger.Printf("[Error]:\n%s\n%s%s", msg, stack, "\033[0m")
_, file, line, _ := runtime.Caller(4)
//nolint
errorKeyBinary := md5.Sum([]byte(e.appService.Name + ":" + file + ":" + fmt.Sprint(line)))
errorKey := hex.EncodeToString(errorKeyBinary[:])
value := &ErrorMessage{
File: file,
Line: line,
AppName: e.appService.Name,
Message: msg,
Stack: stack,
}
if request != nil {
binaryRequest, _ := httputil.DumpRequest(request, true)
if len(binaryRequest) > 2000 {
value.Request = binaryRequest[0:2000]
} else {
value.Request = binaryRequest
}
}
marshalValue, err := json.Marshal(value)
if err != nil {
panic(err)
}
e.redisStorage.HSet(GroupError, errorKey, marshalValue)
e.redisStorage.HSet(GroupError, errorKey+":time", time.Now().Unix())
counter := e.redisStorage.HIncrBy(GroupError, errorKey+":counter", 1)
logg := math.Log10(float64(counter))
if (e.slackService != nil && !e.appService.IsInLocalMode() && !e.appService.IsInTestMode()) && logg == float64(int64(logg)) {
_ = e.slackService.SendToChannel(
e.slackService.GetErrorChannel(),
value.Message,
slackgo.MsgOptionAttachments(
slackgo.Attachment{
AuthorName: e.appService.Name,
Title: "Error link",
TitleLink: e.slackService.GetDevPanelURL() + "#err-" + errorKey,
Text: "Counter: " + fmt.Sprint(counter) + " ENV: " + e.appService.Mode,
},
),
)
}
}
func stack(skip int) []byte {
buf := new(bytes.Buffer)
var lines [][]byte
var lastFile string
for i := skip; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
_, _ = fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
if file != lastFile {
data, err := ioutil.ReadFile(file)
if err != nil {
continue
}
lines = bytes.Split(data, []byte{'\n'})
lastFile = file
}
_, _ = fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
}
return buf.Bytes()
}
func source(lines [][]byte, n int) []byte {
n--
if n < 0 || n >= len(lines) {
return dunno
}
return bytes.TrimSpace(lines[n])
}
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 {
name = name[lastSlash+1:]
}
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, centerDot, dot, -1)
return name
}