forked from goadesign/goa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathappengine.go
80 lines (71 loc) · 1.82 KB
/
appengine.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
// +build appengine
package cellar
import (
"net/http"
"os"
"regexp"
"appengine"
"github.com/raphael/goa"
"github.com/raphael/goa/examples/cellar/controllers"
"gopkg.in/inconshreveable/log15.v2"
)
func init() {
goa.Log.SetHandler(log15.MultiHandler(
log15.StreamHandler(os.Stderr, log15.LogfmtFormat()),
AppEngineLogHandler()),
)
api := controllers.New()
api.Use(AppEngineLogCtx())
api.Use(goa.CORS(corsPath, "*", "", "", "", "GET", ""))
controllers.Mount(api)
http.HandleFunc("/", api.ServeHTTP)
}
// Format used for logging to AppEngine
var logFormat = log15.JsonFormat()
// Paths that must return CORS headers
var corsPath = regexp.MustCompile(`^/(schema|swagger)\.json$`)
// AppEngineLogHandler sends logs to AppEngine.
// The record must contain the appengine request context.
func AppEngineLogHandler() log15.Handler {
return log15.FuncHandler(func(r *log15.Record) error {
var c appengine.Context
index := 0
for i, e := range r.Ctx {
if ct, ok := e.(appengine.Context); ok {
c = ct
index = i
break
}
}
if c == nil {
// not in the context of a request
return nil
}
r.Ctx = append(r.Ctx[:index-1], r.Ctx[index+1:]...)
log := string(logFormat.Format(r))
switch r.Lvl {
case log15.LvlCrit:
c.Criticalf(log)
case log15.LvlError:
c.Errorf(log)
case log15.LvlWarn:
c.Warningf(log)
case log15.LvlInfo:
c.Infof(log)
case log15.LvlDebug:
c.Debugf(log)
}
return nil
})
}
// AppEngineLogCtx returns a goa middleware that sets the appengine context in the log records.
func AppEngineLogCtx() goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx *goa.Context) error {
actx := appengine.NewContext(ctx.Request())
ctx.SetValue(goa.ReqIDKey, appengine.RequestID(actx))
ctx.Logger = ctx.Logger.New("aeCtx", actx)
return h(ctx)
}
}
}