Skip to content

Commit

Permalink
refactor: logger support to get value from context
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Nov 27, 2020
1 parent 17d2b15 commit cc3b31b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ const (
payloadSizeHuman = "payload-size-human"
requestHeader = "requestHeader"
responseHeader = "responseHeader"
context = "context"
httpProto = "HTTP"
httpsProto = "HTTPS"

Expand Down Expand Up @@ -167,6 +168,11 @@ func parseLoggerTags(desc []byte) []*LoggerTag {
category: responseHeader,
data: byteSliceToString(k[1:]),
})
case byte(':'):
arr = append(arr, &LoggerTag{
category: context,
data: byteSliceToString(k[1:]),
})
default:
arr = append(arr, &LoggerTag{
category: byteSliceToString(k),
Expand Down Expand Up @@ -223,6 +229,8 @@ func formatLog(c *elton.Context, tags []*LoggerTag, startedAt time.Time) string
return c.Request.Header.Get(tag.data)
case responseHeader:
return c.GetHeader(tag.data)
case context:
return c.GetString(tag.data)
case referer:
return c.Request.Referer()
case userAgent:
Expand Down
17 changes: 17 additions & 0 deletions middleware/logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,23 @@ func TestLogger(t *testing.T) {
assert.Nil(err)
})

t.Run("context", func(t *testing.T) {
config := LoggerConfig{
Format: "{:id}",
OnLog: func(log string, _ *elton.Context) {
assert.Equal("1", log, "get context value fail")
},
}
m := NewLogger(config)
c := elton.NewContext(nil, nil)
c.Set("id", "1")
c.Next = func() error {
return nil
}
err := m(c)
assert.Nil(err)
})

t.Run("get log function", func(t *testing.T) {
layout := "{host} {remote} {real-ip} {method} {path} {proto} {query} {scheme} {uri} {referer} {userAgent} {size} {size-human} {status} {payload-size} {payload-size-human}"
fn := GenerateLog(layout)
Expand Down

0 comments on commit cc3b31b

Please sign in to comment.