/
logrus.go
67 lines (56 loc) · 1.59 KB
/
logrus.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
package service
import (
"os"
"time"
glogrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
)
// LogInterceptor for gRPC.
type LogInterceptor interface {
Replace()
Unary() grpc.UnaryServerInterceptor
Stream() grpc.StreamServerInterceptor
}
type logrusInterceptor struct {
entry *logrus.Entry
opts []glogrus.Option
}
// NewLogrusInterceptor is gRPC interceptor for logrus.
func NewLogrusInterceptor(l *logrus.Logger) LogInterceptor {
return newLogrusInterceptor(l)
}
func newLogrusInterceptor(l *logrus.Logger) logrusInterceptor {
return logrusInterceptor{
entry: logrus.NewEntry(l),
opts: []glogrus.Option{},
}
}
func (l logrusInterceptor) Replace() {
glogrus.ReplaceGrpcLogger(l.entry)
}
func (l logrusInterceptor) Unary() grpc.UnaryServerInterceptor {
return glogrus.UnaryServerInterceptor(l.entry, l.opts...)
}
func (l logrusInterceptor) Stream() grpc.StreamServerInterceptor {
return glogrus.StreamServerInterceptor(l.entry, l.opts...)
}
func setupLogrus(cfg *Config, logPath string) (*logrus.Logger, logrusInterceptor) {
llog := logrus.StandardLogger()
formatter := &logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: time.RFC3339Nano,
}
llog.SetLevel(logrusFromLevel(cfg.LogLevel()))
llog.SetFormatter(formatter)
// slog.SetReportCaller(true)
if logPath != "" {
logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
if err != nil {
logFatal(err)
}
llog.Infof("Logging to %s", logPath)
llog.SetOutput(logFile)
}
return llog, newLogrusInterceptor(llog)
}