Skip to content

Commit 5f8d783

Browse files
committed
add simple log
1 parent d4d11e1 commit 5f8d783

File tree

8 files changed

+182
-37
lines changed

8 files changed

+182
-37
lines changed

internal/routers/routers.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func NewRouter() *gin.Engine {
4040
// request id middleware
4141
r.Use(middleware.RequestID())
4242

43-
// logger middleware
43+
// logger middleware, to print simple messages, replace middleware.Logging with middleware.SimpleLog
4444
r.Use(middleware.Logging(
4545
middleware.WithLog(logger.Get()),
4646
middleware.WithRequestIDFromContext(),

internal/routers/routers_pbExample.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ func NewRouter_pbExample() *gin.Engine { //nolint
4040
// request id middleware
4141
r.Use(middleware.RequestID())
4242

43-
// logger middleware
43+
// logger middleware, to print simple messages, replace middleware.Logging with middleware.SimpleLog
4444
r.Use(middleware.Logging(
4545
middleware.WithLog(logger.Get()),
4646
middleware.WithRequestIDFromContext(),

internal/server/grpc.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func (s *grpcServer) unaryServerOptions() grpc.ServerOption {
151151
interceptor.UnaryServerRequestID(),
152152
}
153153

154-
// logger interceptor
154+
// logger interceptor, to print simple messages, replace interceptor.UnaryServerLog with interceptor.UnaryServerSimpleLog
155155
unaryServerInterceptors = append(unaryServerInterceptors, interceptor.UnaryServerLog(
156156
logger.Get(),
157157
interceptor.WithReplaceGRPCLogger(),
@@ -210,7 +210,7 @@ func (s *grpcServer) streamServerOptions() grpc.ServerOption {
210210
//interceptor.StreamServerRequestID(),
211211
}
212212

213-
// logger interceptor
213+
// logger interceptor, to print simple messages, replace interceptor.StreamServerLog with interceptor.StreamServerSimpleLog
214214
streamServerInterceptors = append(streamServerInterceptors, interceptor.StreamServerLog(
215215
logger.Get(),
216216
interceptor.WithReplaceGRPCLogger(),
@@ -237,7 +237,6 @@ func (s *grpcServer) streamServerOptions() grpc.ServerOption {
237237
// metrics interceptor
238238
if config.Get().App.EnableMetrics {
239239
streamServerInterceptors = append(streamServerInterceptors, interceptor.StreamServerMetrics())
240-
s.registerMetricsMuxAndMethodFunc = s.registerMetricsMuxAndMethod()
241240
}
242241

243242
// limit interceptor

pkg/gin/middleware/README.md

Lines changed: 38 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,40 @@
11
## middleware
22

3-
gin middleware plugin.
3+
Gin middleware plugin.
44

55
<br>
66

77
## Example of use
88

99
### logging middleware
1010

11-
You can set the maximum length for printing, add a request id field, ignore print path, customize [zap](go.uber.org/zap) log
11+
You can set the maximum length for printing, add a request id field, ignore print path, customize [zap](go.uber.org/zap) log.
1212

1313
```go
14+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
15+
1416
r := gin.Default()
15-
16-
r.Use(middleware.Logging())
1717

18-
r.Use(middleware.Logging(
18+
// default
19+
r.Use(middleware.Logging()) // simplified logging using middleware.SimpleLog()
20+
21+
// custom
22+
r.Use(middleware.Logging( // simplified logging using middleware.SimpleLog(WithRequestIDFromHeader())
1923
middleware.WithMaxLen(400),
20-
//WithRequestIDFromHeader(),
21-
WithRequestIDFromContext(),
24+
WithRequestIDFromHeader(),
25+
//WithRequestIDFromContext(),
26+
//middleware.WithLog(log), // custom zap log
2227
//middleware.WithIgnoreRoutes("/hello"),
2328
))
24-
25-
log, _ := logger.Init(logger.WithFormat("json"))
26-
r.Use(middlewareLogging(
27-
middleware.WithLog(log),
28-
))
2929
```
3030

3131
<br>
3232

3333
### Allow cross-domain requests middleware
3434

3535
```go
36+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
37+
3638
r := gin.Default()
3739
r.Use(middleware.Cors())
3840
```
@@ -44,17 +46,19 @@ You can set the maximum length for printing, add a request id field, ignore prin
4446
Adaptive flow limitation based on hardware resources.
4547

4648
```go
49+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
50+
4751
r := gin.Default()
4852

4953
// e.g. (1) use default
50-
// r.Use(RateLimit())
54+
// r.Use(middleware.RateLimit())
5155

5256
// e.g. (2) custom parameters
53-
r.Use(RateLimit(
54-
WithWindow(time.Second*10),
55-
WithBucket(100),
56-
WithCPUThreshold(100),
57-
WithCPUQuota(0.5),
57+
r.Use(middleware.RateLimit(
58+
WithWindow(time.Second*10),
59+
WithBucket(100),
60+
WithCPUThreshold(100),
61+
WithCPUQuota(0.5),
5862
))
5963
```
6064

@@ -63,9 +67,12 @@ Adaptive flow limitation based on hardware resources.
6367
### Circuit Breaker middleware
6468

6569
```go
70+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
71+
6672
r := gin.Default()
67-
r.Use(CircuitBreaker())
73+
r.Use(middleware.CircuitBreaker())
6874
```
75+
6976
<br>
7077

7178
### jwt authorization middleware
@@ -74,6 +81,7 @@ Adaptive flow limitation based on hardware resources.
7481

7582
```go
7683
import "github.com/zhufuyi/sponge/pkg/jwt"
84+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
7785

7886
func main() {
7987
r := gin.Default()
@@ -102,12 +110,14 @@ func Login(c *gin.Context) {
102110
// save token
103111
}
104112
```
113+
105114
<br>
106115

107116
#### custom authorization
108117

109118
```go
110119
import "github.com/zhufuyi/sponge/pkg/jwt"
120+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
111121

112122
func main() {
113123
r := gin.Default()
@@ -153,6 +163,9 @@ func Login(c *gin.Context) {
153163
### tracing middleware
154164

155165
```go
166+
import "github.com/zhufuyi/sponge/pkg/tracer"
167+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
168+
156169
func InitTrace(serviceName string) {
157170
exporter, err := tracer.NewJaegerAgentExporter("192.168.3.37", "6831")
158171
if err != nil {
@@ -192,6 +205,8 @@ func SpanDemo(serviceName string, spanName string, ctx context.Context) {
192205
### Metrics middleware
193206

194207
```go
208+
import "github.com/zhufuyi/sponge/pkg/gin/middleware/metrics"
209+
195210
r := gin.Default()
196211

197212
r.Use(metrics.Metrics(r,
@@ -205,11 +220,13 @@ func SpanDemo(serviceName string, spanName string, ctx context.Context) {
205220
### Request id
206221

207222
```go
223+
import "github.com/zhufuyi/sponge/pkg/gin/middleware"
224+
208225
r := gin.Default()
209-
r.Use(RequestID())
226+
r.Use(middleware.RequestID())
210227

211228
// Customized request id key
212-
//r.User(RequestID(
229+
//r.User(middleware.RequestID(
213230
// middleware.WithContextRequestIDKey("your ctx request id key"), // default is request_id
214231
// middleware.WithHeaderRequestIDKey("your header request id key"), // default is X-Request-Id
215232
//))

pkg/gin/middleware/logging.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,3 +182,46 @@ func Logging(opts ...Option) gin.HandlerFunc {
182182
o.log.Info(">>>>", fields...)
183183
}
184184
}
185+
186+
// SimpleLog print response info
187+
func SimpleLog(opts ...Option) gin.HandlerFunc {
188+
o := defaultOptions()
189+
o.apply(opts...)
190+
191+
return func(c *gin.Context) {
192+
start := time.Now()
193+
194+
// ignore printing of the specified route
195+
if _, ok := o.ignoreRoutes[c.Request.URL.Path]; ok {
196+
c.Next()
197+
return
198+
}
199+
200+
reqID := ""
201+
if o.requestIDFrom == 1 {
202+
if v, isExist := c.Get(ContextRequestIDKey); isExist {
203+
if requestID, ok := v.(string); ok {
204+
reqID = requestID
205+
}
206+
}
207+
} else if o.requestIDFrom == 2 {
208+
reqID = c.Request.Header.Get(HeaderXRequestIDKey)
209+
}
210+
211+
// processing requests
212+
c.Next()
213+
214+
// print return message after processing
215+
fields := []zap.Field{
216+
zap.Int("code", c.Writer.Status()),
217+
zap.String("method", c.Request.Method),
218+
zap.String("url", c.Request.URL.String()),
219+
zap.Int64("time_us", time.Since(start).Microseconds()),
220+
zap.Int("size", c.Writer.Size()),
221+
}
222+
if reqID != "" {
223+
fields = append(fields, zap.String(ContextRequestIDKey, reqID))
224+
}
225+
o.log.Info("[GIN]", fields...)
226+
}
227+
}

pkg/gin/middleware/logging_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ func runLogHTTPServer2() string {
157157
gin.SetMode(gin.ReleaseMode)
158158
r := gin.Default()
159159
r.Use(RequestID())
160-
r.Use(Logging(
160+
r.Use(SimpleLog(
161161
WithLog(logger.Get()),
162162
WithMaxLen(200),
163163
WithRequestIDFromContext(),

0 commit comments

Comments
 (0)