Skip to content

Commit 1fa9fcc

Browse files
committed
feat: support echo
1 parent cdd18f7 commit 1fa9fcc

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

middleware.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"strings"
1111
"time"
1212

13+
"github.com/labstack/echo/v4"
1314
"go.opencensus.io/exporter/stackdriver/propagation"
1415
"go.opencensus.io/trace"
1516
)
@@ -56,6 +57,39 @@ func RequestLogging(config *Config) func(http.Handler) http.Handler {
5657
}
5758
}
5859

60+
// RequestLoggingWithEcho creates the middleware which logs a request log and creates a request-context logger
61+
func RequestLoggingWithEcho(config *Config) echo.MiddlewareFunc {
62+
return func(next echo.HandlerFunc) echo.HandlerFunc {
63+
fn := func(c echo.Context) error {
64+
r := c.Request()
65+
traceId := getTraceId(r)
66+
if traceId == "" {
67+
// there is no span yet, so create one
68+
var ctx context.Context
69+
traceId, ctx = generateTraceId(r)
70+
r = r.WithContext(ctx)
71+
}
72+
73+
traces := fmt.Sprintf("projects/%s/traces/%s", config.ProjectId, traceId)
74+
75+
contextLogger := &ContextLogger{
76+
out: config.ContextLogOut,
77+
Trace: traces,
78+
Severity: config.Severity,
79+
AdditionalData: config.AdditionalData,
80+
loggedSeverity: make([]Severity, 0, 10),
81+
Skip: config.Skip,
82+
}
83+
ctx := context.WithValue(r.Context(), contextLoggerKey, contextLogger)
84+
85+
r = r.WithContext(ctx)
86+
c.SetRequest(r)
87+
return next(c)
88+
}
89+
return fn
90+
}
91+
}
92+
5993
func getTraceId(r *http.Request) string {
6094
span := trace.FromContext(r.Context())
6195
if span != nil {

0 commit comments

Comments
 (0)