git.zd.zone/hrpc/hrpc@v0.0.12/log/log.go (about) 1 package log 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "path/filepath" 8 "runtime" 9 "time" 10 11 "git.zd.zone/hrpc/hrpc/codec" 12 "git.zd.zone/hrpc/hrpc/utils/location" 13 "github.com/sirupsen/logrus" 14 "google.golang.org/grpc" 15 ) 16 17 func init() { 18 if err := location.New().Load(); err != nil { 19 panic(err) 20 } 21 setup() 22 } 23 24 var ( 25 logger = logrus.New() 26 option = Option{ 27 Formatter: &logrus.JSONFormatter{}, 28 Outer: os.Stdout, 29 Environment: "Unknown", 30 StackSkip: 1, 31 } 32 ) 33 34 func setup() { 35 logger.SetReportCaller(!option.DisableReportCaller) 36 logger.SetFormatter(option.Formatter) 37 for _, hook := range option.Hooks { 38 if err := hook.Establish(); err != nil { 39 fmt.Println("** establishing log failed, " + err.Error()) 40 } 41 logger.AddHook(hook) 42 } 43 logger.Out = option.Outer 44 } 45 46 func WithFields(ctx context.Context, fields ...interface{}) *logrus.Entry { 47 _, file, line, _ := runtime.Caller(option.StackSkip) 48 msg := codec.Message(ctx) 49 params := logrus.Fields{ 50 "category": "system", 51 "trace_id": msg.TraceID(), 52 "pst_time": time.Now().In(location.PST()).Format("2006-01-02 15:04:05"), 53 "bj_time": time.Now().In(location.BJS()).Format("2006-01-02 15:04:05"), 54 "file_name": fmt.Sprintf("%s:%d", filepath.Base(file), line), 55 "package": filepath.Base(filepath.Dir(file)), 56 "environment": option.Environment, 57 "server_name": msg.ServerName(), 58 } 59 if len(fields)%2 != 0 { 60 // fields should exist in pair 61 return logger.WithFields(params) 62 } 63 for i := 0; i < len(fields); { 64 key := "unknown" 65 if k, ok := fields[i].(string); ok { 66 key = k 67 } 68 params[key] = fields[i+1] 69 i += 2 70 } 71 return logger.WithFields(params) 72 } 73 74 func AuditLog(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 75 msg := codec.Message(ctx) 76 interceptorEntry( 77 "trace_id", msg.TraceID(), 78 "method", info.FullMethod, 79 "direction", "incoming", 80 ).Infoln(req) 81 resp, err := handler(ctx, req) 82 interceptorEntry( 83 "trace_id", msg.TraceID(), 84 "method", info.FullMethod, 85 "direction", "outcoming", 86 "error", err, 87 ).Infoln(resp) 88 return resp, err 89 } 90 91 func interceptorEntry(fields ...interface{}) *logrus.Entry { 92 params := logrus.Fields{ 93 "category": "audit", 94 "pst_time": time.Now().In(location.PST()).Format("2006-01-02 15:04:05"), 95 "bj_time": time.Now().In(location.BJS()).Format("2006-01-02 15:04:05"), 96 } 97 if len(fields)%2 != 0 { 98 // fields should exist in pair 99 return logger.WithFields(params) 100 } 101 for i := 0; i < len(fields); { 102 key := "unknown" 103 if k, ok := fields[i].(string); ok { 104 key = k 105 } 106 params[key] = fields[i+1] 107 i += 2 108 } 109 return logger.WithFields(params) 110 }