-
Notifications
You must be signed in to change notification settings - Fork 3
/
logging.go
60 lines (50 loc) · 1.21 KB
/
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
52
53
54
55
56
57
58
59
60
package main
import (
"context"
"os"
"time"
"github.com/aws/aws-lambda-go/lambdacontext"
"github.com/sirupsen/logrus"
"github.com/rybit/lambdalogger/version"
)
type LogConfig struct {
LogLevel string `split_words:"true"`
LogFormat string `split_words:"true"`
}
func NewLogger(cfg *LogConfig) *logrus.Entry {
log := logrus.New()
log.Out = os.Stdout
if cfg.LogFormat == "json" {
log.Formatter = &logrus.JSONFormatter{
TimestampFormat: time.RFC3339Nano,
}
} else {
log.Formatter = &logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: time.RFC3339Nano,
QuoteEmptyFields: true,
}
}
if cfg.LogLevel != "" {
if lvl, err := logrus.ParseLevel(cfg.LogLevel); err != nil {
log.WithError(err).Warnf("Failed to parse '%s' into a log level - ignoring completely", cfg.LogLevel)
} else {
log.SetLevel(lvl)
}
}
entry := log.WithFields(logrus.Fields{
"sha": version.SHA,
"tag": version.Tag,
})
entry.WithFields(logrus.Fields{
"log_format": cfg.LogFormat,
"log_level": cfg.LogLevel,
}).Debugf("Logger created")
return entry
}
func RequestID(ctx context.Context) string {
if lctx, ok := lambdacontext.FromContext(ctx); ok {
return lctx.AwsRequestID
}
return "unknown"
}