forked from digitalocean/go-workers2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware_logging.go
51 lines (40 loc) · 1.05 KB
/
middleware_logging.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
package workers
import (
"fmt"
"log"
"runtime"
"time"
)
// LogMiddleware is the default logging middleware
func LogMiddleware(queue string, mgr *Manager, next JobFunc) JobFunc {
return func(message *Msg) (err error) {
prefix := fmt.Sprint(queue, " JID-", message.Jid())
start := time.Now()
mgr.logger.Println(prefix, "start")
mgr.logger.Println(prefix, "args:", message.Args().ToJson())
defer func() {
if e := recover(); e != nil {
var ok bool
if err, ok = e.(error); !ok {
err = fmt.Errorf("%v", e)
}
if err != nil {
logProcessError(mgr.logger, prefix, start, err)
}
}
}()
err = next(message)
if err != nil {
logProcessError(mgr.logger, prefix, start, err)
} else {
mgr.logger.Println(prefix, "done:", time.Since(start))
}
return
}
}
func logProcessError(logger *log.Logger, prefix string, start time.Time, err error) {
logger.Println(prefix, "fail:", time.Since(start))
buf := make([]byte, 4096)
buf = buf[:runtime.Stack(buf, false)]
logger.Printf("%s error: %v\n%s", prefix, err, buf)
}