|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "math" |
| 6 | + "strings" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/gin-gonic/gin" |
| 10 | + "github.com/pkg/errors" |
| 11 | + "github.com/uptrace/opentelemetry-go-extra/otelzap" |
| 12 | + "go.uber.org/zap" |
| 13 | +) |
| 14 | + |
| 15 | +func LoggerMiddleware(logger *otelzap.Logger) gin.HandlerFunc { |
| 16 | + return func(c *gin.Context) { |
| 17 | + logger := logger.Ctx(c.Request.Context()).WithOptions(zap.AddStacktrace(zap.FatalLevel)) |
| 18 | + c.Next() |
| 19 | + |
| 20 | + fields := []zap.Field{} |
| 21 | + fields = append(fields, basicFields(c)...) |
| 22 | + fields = append(fields, pathFields(c)...) |
| 23 | + fields = append(fields, queryFields(c)...) |
| 24 | + fields = append(fields, errorFields(c)...) |
| 25 | + |
| 26 | + if c.Writer.Status() >= 500 { |
| 27 | + logger.Error("request completed", fields...) |
| 28 | + } else { |
| 29 | + logger.Info("request completed", fields...) |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func basicFields(c *gin.Context) []zap.Field { |
| 35 | + return []zap.Field{ |
| 36 | + zap.String("method", c.Request.Method), |
| 37 | + zap.Int("status", c.Writer.Status()), |
| 38 | + zap.Float64("latency_ms", math.Round(float64(GetRequestLatency(c))/float64(time.Millisecond)*100)/100), |
| 39 | + zap.String("client_ip", c.ClientIP()), |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +func pathFields(c *gin.Context) []zap.Field { |
| 44 | + rawPath := c.Request.URL.Path |
| 45 | + normalizedPath := rawPath |
| 46 | + params := make(map[string]string) |
| 47 | + for _, p := range c.Params { |
| 48 | + normalizedPath = strings.Replace(normalizedPath, p.Value, ":"+p.Key, 1) |
| 49 | + params[p.Key] = p.Value |
| 50 | + } |
| 51 | + |
| 52 | + fields := []zap.Field{ |
| 53 | + zap.String("path", normalizedPath), |
| 54 | + zap.String("raw_path", rawPath), |
| 55 | + } |
| 56 | + |
| 57 | + if len(params) > 0 { |
| 58 | + fields = append(fields, zap.Any("params", params)) |
| 59 | + } |
| 60 | + |
| 61 | + return fields |
| 62 | +} |
| 63 | + |
| 64 | +func queryFields(c *gin.Context) []zap.Field { |
| 65 | + if c.Request.URL.RawQuery == "" { |
| 66 | + return nil |
| 67 | + } |
| 68 | + return []zap.Field{ |
| 69 | + zap.String("query", c.Request.URL.RawQuery), |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +func errorFields(c *gin.Context) []zap.Field { |
| 74 | + if len(c.Errors) == 0 { |
| 75 | + return nil |
| 76 | + } |
| 77 | + |
| 78 | + err := c.Errors.Last().Err |
| 79 | + if c.Writer.Status() >= 500 { |
| 80 | + return getErrorFields(err) |
| 81 | + } |
| 82 | + return []zap.Field{ |
| 83 | + zap.String("error", err.Error()), |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +func getErrorFields(err error) []zap.Field { |
| 88 | + var originalErr error |
| 89 | + |
| 90 | + // If it's our ErrorResponse, get the inner error |
| 91 | + if errResp, ok := err.(ErrorResponse); ok { |
| 92 | + err = errResp.Err |
| 93 | + } |
| 94 | + |
| 95 | + // Keep the wrapped error for stack trace but get original for type/message |
| 96 | + wrappedErr := err |
| 97 | + if cause := errors.Unwrap(err); cause != nil { |
| 98 | + originalErr = cause |
| 99 | + } else { |
| 100 | + originalErr = err |
| 101 | + } |
| 102 | + |
| 103 | + fields := []zap.Field{ |
| 104 | + zap.String("error", originalErr.Error()), |
| 105 | + zap.String("error_type", fmt.Sprintf("%T", originalErr)), |
| 106 | + } |
| 107 | + |
| 108 | + // Get the stack trace from the wrapped error |
| 109 | + type stackTracer interface { |
| 110 | + StackTrace() errors.StackTrace |
| 111 | + } |
| 112 | + var st stackTracer |
| 113 | + if errors.As(wrappedErr, &st) { |
| 114 | + trace := fmt.Sprintf("%+v", st.StackTrace()) |
| 115 | + lines := strings.Split(trace, "\n") |
| 116 | + var filtered []string |
| 117 | + |
| 118 | + for i := 0; i < len(lines); i++ { |
| 119 | + line := lines[i] |
| 120 | + if strings.Contains(line, "github.com/hookdeck/outpost") { |
| 121 | + filtered = append(filtered, line) |
| 122 | + // Include the next line if it's a file path |
| 123 | + if i+1 < len(lines) && strings.HasPrefix(lines[i+1], "\t") { |
| 124 | + filtered = append(filtered, lines[i+1]) |
| 125 | + } |
| 126 | + // Stop at the first handler |
| 127 | + if strings.Contains(line, "Handler") { |
| 128 | + break |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + if len(filtered) > 0 { |
| 134 | + fields = append(fields, zap.String("error_trace", strings.Join(filtered, "\n"))) |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + return fields |
| 139 | +} |
0 commit comments