32 lines
816 B
Go
32 lines
816 B
Go
package handler
|
|
|
|
import (
|
|
"time"
|
|
|
|
"git.yuntuo.hk/k2safe/go-omni"
|
|
"git.yuntuo.hk/k2safe/go-omni/logx"
|
|
)
|
|
|
|
// RequestLog demonstrates business middleware using only the GoOmni API.
|
|
func RequestLog(logger *logx.Logger) omni.Middleware {
|
|
return func(next omni.Handler) omni.Handler {
|
|
return func(ctx *omni.Context) error {
|
|
started := time.Now()
|
|
err := next(ctx)
|
|
attributes := []any{
|
|
"requestId", ctx.RequestID(),
|
|
"method", ctx.Request().Method,
|
|
"path", ctx.Request().URL.Path,
|
|
"duration", time.Since(started),
|
|
}
|
|
if err != nil {
|
|
attributes = append(attributes, "error", err)
|
|
logger.ErrorContext(ctx.Request().Context(), "request failed", attributes...)
|
|
} else {
|
|
logger.InfoContext(ctx.Request().Context(), "request completed", attributes...)
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
}
|