-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover.go
63 lines (51 loc) · 1.63 KB
/
recover.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
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package recover provides recovery for specific routes or for the whole app via middleware. See _examples/beginner/recover
package recover
import (
"fmt"
"runtime"
"strconv"
"github.com/go-siris/siris/context"
)
func getRequestLogs(ctx context.Context) string {
var status, ip, method, path string
status = strconv.Itoa(ctx.GetStatusCode())
path = ctx.Path()
method = ctx.Method()
ip = ctx.RemoteAddr()
// the date should be logged by siris' Logger, so we skip them
return fmt.Sprintf("%v %s %s %s", status, path, method, ip)
}
// New returns a new recover middleware
// it logs to the LoggerOut siris' configuration field if its IsDeveloper configuration field is enabled.
// otherwise it just continues to serve
func New() context.Handler {
return func(ctx context.Context) {
defer func() {
if err := recover(); err != nil {
if ctx.IsStopped() {
return
}
var stacktrace string
for i := 1; ; i++ {
_, f, l, got := runtime.Caller(i)
if !got {
break
}
stacktrace += fmt.Sprintf("%s:%d\n", f, l)
}
// when stack finishes
logMessage := fmt.Sprintf("Recovered from a route's Handler('%s')\n", ctx.HandlerName())
logMessage += fmt.Sprintf("At Request: %s\n", getRequestLogs(ctx))
logMessage += fmt.Sprintf("Trace: %s\n", err)
logMessage += fmt.Sprintf("\n%s\n", stacktrace)
ctx.Application().Logger().Warn(logMessage)
ctx.StopExecution()
ctx.StatusCode(500)
}
}()
ctx.Next()
}
}