From 37c1694ae81d71695cc3ae8d9c372c57a2fb0713 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Mon, 7 Dec 2020 15:22:17 +0800 Subject: [PATCH 1/9] feat: access log --- api/conf/conf.go | 20 +++++++++++- api/filter/logging.go | 72 ++++++++++++++++++++++++++++++++++++++++++- api/internal/route.go | 2 +- 3 files changed, 91 insertions(+), 3 deletions(-) diff --git a/api/conf/conf.go b/api/conf/conf.go index 91eb89bc21..85b4004ed9 100644 --- a/api/conf/conf.go +++ b/api/conf/conf.go @@ -48,6 +48,7 @@ var ( ETCDEndpoints = []string{"127.0.0.1:2379"} ErrorLogLevel = "warn" ErrorLogPath = "logs/error.log" + AccessLogPath = "logs/access.log" UserList = make(map[string]User, 2) AuthConf Authentication SSLDefaultStatus = 1 //enable ssl by default @@ -67,8 +68,14 @@ type ErrorLog struct { FilePath string `yaml:"file_path"` } +type AccessLog struct { + Level string + FilePath string `yaml:"file_path"` +} + type Log struct { - ErrorLog ErrorLog `yaml:"error_log"` + ErrorLog ErrorLog `yaml:"error_log"` + AccessLog AccessLog `yaml:"access_log"` } type Conf struct { @@ -147,6 +154,17 @@ func setConf() { } } + // access log + if config.Conf.Log.AccessLog.FilePath != "" { + AccessLogPath = config.Conf.Log.AccessLog.FilePath + } + if !filepath.IsAbs(AccessLogPath) { + AccessLogPath, err = filepath.Abs(WorkDir + "/" + AccessLogPath) + if err != nil { + panic(err) + } + } + //auth initAuthentication(config.Authentication) } diff --git a/api/filter/logging.go b/api/filter/logging.go index 328ac4dc6d..4daa9153ff 100644 --- a/api/filter/logging.go +++ b/api/filter/logging.go @@ -16,4 +16,74 @@ */ package filter -//for logging access log, will refactor it in a new pr. +import ( + "bytes" + "io/ioutil" + "time" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" + + "github.com/apisix/manager-api/log" +) + +var logger *zap.SugaredLogger + +func RequestLogHandler() gin.HandlerFunc { + return func(c *gin.Context) { + start, host, remoteIP, path, method := time.Now(), c.Request.Host, c.ClientIP(), c.Request.URL.Path, c.Request.Method + var val interface{} + if method == "GET" { + val = c.Request.URL.Query() + } else { + val, _ = c.GetRawData() + // set RequestBody back + c.Request.Body = ioutil.NopCloser(bytes.NewReader(val.([]byte))) + } + c.Set("requestBody", val) + uuid := c.Writer.Header().Get("X-Request-Id") + + param, _ := c.Get("requestBody") + + switch paramType := param.(type) { + case []byte: + param = string(param.([]byte)) + log.Infof("type of param: %#v", paramType) + default: + } + + blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} + c.Writer = blw + c.Next() + latency := time.Since(start) / 1000000 + statusCode := c.Writer.Status() + respBody := blw.body.String() + + var errs []string + for _, err := range c.Errors { + errs = append(errs, err.Error()) + } + log.Info("", + zap.String("requestId", uuid), + zap.Duration("latency", latency), + zap.String("remoteIP", remoteIP), + zap.String("method", method), + zap.String("path", path), + zap.Int("statusCode", statusCode), + zap.String("host", host), + //zap.String("param", param.(string)), + zap.String("respBody", respBody), + zap.Strings("errs", errs), + ) + } +} + +type bodyLogWriter struct { + gin.ResponseWriter + body *bytes.Buffer +} + +func (w bodyLogWriter) Write(b []byte) (int, error) { + w.body.Write(b) + return w.ResponseWriter.Write(b) +} diff --git a/api/internal/route.go b/api/internal/route.go index 04a721f654..1043efd751 100644 --- a/api/internal/route.go +++ b/api/internal/route.go @@ -46,7 +46,7 @@ func SetUpRouter() *gin.Engine { r := gin.New() store := cookie.NewStore([]byte("secret")) r.Use(sessions.Sessions("session", store)) - r.Use(filter.CORS(), filter.Authentication(), filter.RequestId(), filter.RecoverHandler()) + r.Use(filter.CORS(), filter.RequestLogHandler(), filter.Authentication(), filter.RequestId(), filter.RecoverHandler()) r.Use(static.Serve("/", static.LocalFile(conf.WebDir, false))) r.NoRoute(func(c *gin.Context) { c.File(fmt.Sprintf("%s/index.html", conf.WebDir)) From 64d8285429db0dd5c2893782f4965ecad1fe6b16 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Tue, 8 Dec 2020 09:19:12 +0800 Subject: [PATCH 2/9] feat: access log --- api/filter/logging.go | 6 ++---- api/internal/route.go | 4 +++- api/log/zap.go | 25 +++++++++++++++++++------ api/test/shell/cli_test.sh | 4 ++-- 4 files changed, 26 insertions(+), 13 deletions(-) diff --git a/api/filter/logging.go b/api/filter/logging.go index 4daa9153ff..8283d437f4 100644 --- a/api/filter/logging.go +++ b/api/filter/logging.go @@ -27,9 +27,8 @@ import ( "github.com/apisix/manager-api/log" ) -var logger *zap.SugaredLogger -func RequestLogHandler() gin.HandlerFunc { +func RequestLogHandler(logger *zap.SugaredLogger) gin.HandlerFunc { return func(c *gin.Context) { start, host, remoteIP, path, method := time.Now(), c.Request.Host, c.ClientIP(), c.Request.URL.Path, c.Request.Method var val interface{} @@ -63,12 +62,11 @@ func RequestLogHandler() gin.HandlerFunc { for _, err := range c.Errors { errs = append(errs, err.Error()) } - log.Info("", + logger.Info(path, zap.String("requestId", uuid), zap.Duration("latency", latency), zap.String("remoteIP", remoteIP), zap.String("method", method), - zap.String("path", path), zap.Int("statusCode", statusCode), zap.String("host", host), //zap.String("param", param.(string)), diff --git a/api/internal/route.go b/api/internal/route.go index 1043efd751..9117bfdaeb 100644 --- a/api/internal/route.go +++ b/api/internal/route.go @@ -18,6 +18,7 @@ package internal import ( "fmt" + "github.com/apisix/manager-api/log" "github.com/gin-contrib/pprof" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" @@ -44,9 +45,10 @@ func SetUpRouter() *gin.Engine { gin.SetMode(gin.ReleaseMode) } r := gin.New() + logger := log.GetLogger("access") store := cookie.NewStore([]byte("secret")) r.Use(sessions.Sessions("session", store)) - r.Use(filter.CORS(), filter.RequestLogHandler(), filter.Authentication(), filter.RequestId(), filter.RecoverHandler()) + r.Use(filter.CORS(), filter.RequestLogHandler(logger), filter.Authentication(), filter.RequestId(), filter.RecoverHandler()) r.Use(static.Serve("/", static.LocalFile(conf.WebDir, false))) r.NoRoute(func(c *gin.Context) { c.File(fmt.Sprintf("%s/index.html", conf.WebDir)) diff --git a/api/log/zap.go b/api/log/zap.go index 223a71fb64..d88e5e6a99 100644 --- a/api/log/zap.go +++ b/api/log/zap.go @@ -28,14 +28,22 @@ import ( var logger *zap.SugaredLogger func init() { - writeSyncer := fileWriter() + logger = GetLogger("error") +} + +func GetLogger (logType string) *zap.SugaredLogger{ + writeSyncer := fileWriter(logType) encoder := getEncoder() logLevel := getLogLevel() + if logType == "access" { + logLevel = zapcore.InfoLevel + } + core := zapcore.NewCore(encoder, writeSyncer, logLevel) zapLogger := zap.New(core, zap.AddCaller()) - logger = zapLogger.Sugar() + return zapLogger.Sugar() } func getLogLevel() zapcore.LevelEnabler { @@ -64,16 +72,21 @@ func getEncoder() zapcore.Encoder { return zapcore.NewConsoleEncoder(encoderConfig) } -func fileWriter() zapcore.WriteSyncer { + +func fileWriter(logType string) zapcore.WriteSyncer { + logPath := conf.ErrorLogPath + if logType == "access" { + logPath = conf.AccessLogPath + } //standard output - if conf.ErrorLogPath == "/dev/stdout" { + if logPath == "/dev/stdout" { return zapcore.Lock(os.Stdout) } - if conf.ErrorLogPath == "/dev/stderr" { + if logPath == "/dev/stderr" { return zapcore.Lock(os.Stderr) } - writer, _, err := zap.Open(conf.ErrorLogPath) + writer, _, err := zap.Open(logPath) if err != nil { panic(err) } diff --git a/api/test/shell/cli_test.sh b/api/test/shell/cli_test.sh index 8f142b1909..7b60e60369 100755 --- a/api/test/shell/cli_test.sh +++ b/api/test/shell/cli_test.sh @@ -41,7 +41,7 @@ trap clean_up EXIT export GO111MODULE=on go build -o ./manager-api . -#default level: warn, path: logs/error.log +# default level: warn, path: logs/error.log ./manager-api & sleep 3 @@ -79,7 +79,7 @@ fi clean_logfile -#change path +# change path sed -i 's/logs\/error.log/.\/error.log/' conf/conf.yaml From ab3fe0c530ac1b26845d4ceb3ebba4f046afff8d Mon Sep 17 00:00:00 2001 From: nic-chen Date: Wed, 9 Dec 2020 16:12:01 +0800 Subject: [PATCH 3/9] chore: access log format --- api/filter/logging.go | 35 ++++++++--------------------------- api/internal/route.go | 4 ++-- api/log/log.go | 7 +++++++ api/log/zap.go | 10 +++++----- api/main.go | 5 +++-- 5 files changed, 25 insertions(+), 36 deletions(-) diff --git a/api/filter/logging.go b/api/filter/logging.go index 8283d437f4..ee2ef7d1b5 100644 --- a/api/filter/logging.go +++ b/api/filter/logging.go @@ -18,59 +18,40 @@ package filter import ( "bytes" - "io/ioutil" "time" "github.com/gin-gonic/gin" "go.uber.org/zap" - - "github.com/apisix/manager-api/log" ) func RequestLogHandler(logger *zap.SugaredLogger) gin.HandlerFunc { return func(c *gin.Context) { start, host, remoteIP, path, method := time.Now(), c.Request.Host, c.ClientIP(), c.Request.URL.Path, c.Request.Method - var val interface{} - if method == "GET" { - val = c.Request.URL.Query() - } else { - val, _ = c.GetRawData() - // set RequestBody back - c.Request.Body = ioutil.NopCloser(bytes.NewReader(val.([]byte))) - } - c.Set("requestBody", val) - uuid := c.Writer.Header().Get("X-Request-Id") - - param, _ := c.Get("requestBody") - - switch paramType := param.(type) { - case []byte: - param = string(param.([]byte)) - log.Infof("type of param: %#v", paramType) - default: - } + query := c.Request.URL.RawQuery + requestId := c.Writer.Header().Get("X-Request-Id") blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} c.Writer = blw c.Next() latency := time.Since(start) / 1000000 statusCode := c.Writer.Status() - respBody := blw.body.String() + //respBody := blw.body.String() var errs []string for _, err := range c.Errors { errs = append(errs, err.Error()) } + logger.Info(path, - zap.String("requestId", uuid), + zap.String("requestId", requestId), zap.Duration("latency", latency), zap.String("remoteIP", remoteIP), zap.String("method", method), - zap.Int("statusCode", statusCode), + zap.Int("status", statusCode), zap.String("host", host), - //zap.String("param", param.(string)), - zap.String("respBody", respBody), + zap.String("query", query), + //zap.String("respBody", respBody), zap.Strings("errs", errs), ) } diff --git a/api/internal/route.go b/api/internal/route.go index 9117bfdaeb..5b1b10646f 100644 --- a/api/internal/route.go +++ b/api/internal/route.go @@ -18,7 +18,6 @@ package internal import ( "fmt" - "github.com/apisix/manager-api/log" "github.com/gin-contrib/pprof" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/cookie" @@ -36,6 +35,7 @@ import ( "github.com/apisix/manager-api/internal/handler/service" "github.com/apisix/manager-api/internal/handler/ssl" "github.com/apisix/manager-api/internal/handler/upstream" + "github.com/apisix/manager-api/log" ) func SetUpRouter() *gin.Engine { @@ -45,7 +45,7 @@ func SetUpRouter() *gin.Engine { gin.SetMode(gin.ReleaseMode) } r := gin.New() - logger := log.GetLogger("access") + logger := log.GetLogger(log.AccessLog) store := cookie.NewStore([]byte("secret")) r.Use(sessions.Sessions("session", store)) r.Use(filter.CORS(), filter.RequestLogHandler(logger), filter.Authentication(), filter.RequestId(), filter.RecoverHandler()) diff --git a/api/log/log.go b/api/log/log.go index 3c53a96375..43bb6095b3 100644 --- a/api/log/log.go +++ b/api/log/log.go @@ -20,6 +20,13 @@ var ( DefLogger Interface = emptyLog{} ) +type Type int8 + +const ( + AccessLog Type = iota - 1 + ErrorLog +) + type emptyLog struct { } diff --git a/api/log/zap.go b/api/log/zap.go index d88e5e6a99..deb8de8fac 100644 --- a/api/log/zap.go +++ b/api/log/zap.go @@ -28,14 +28,14 @@ import ( var logger *zap.SugaredLogger func init() { - logger = GetLogger("error") + logger = GetLogger(ErrorLog) } -func GetLogger (logType string) *zap.SugaredLogger{ +func GetLogger (logType Type) *zap.SugaredLogger{ writeSyncer := fileWriter(logType) encoder := getEncoder() logLevel := getLogLevel() - if logType == "access" { + if logType == AccessLog { logLevel = zapcore.InfoLevel } @@ -73,9 +73,9 @@ func getEncoder() zapcore.Encoder { } -func fileWriter(logType string) zapcore.WriteSyncer { +func fileWriter(logType Type) zapcore.WriteSyncer { logPath := conf.ErrorLogPath - if logType == "access" { + if logType == AccessLog { logPath = conf.AccessLogPath } //standard output diff --git a/api/main.go b/api/main.go index ce05fddf34..b3cb8e601e 100644 --- a/api/main.go +++ b/api/main.go @@ -19,18 +19,19 @@ package main import ( "context" "fmt" - "github.com/apisix/manager-api/internal/handler" - "github.com/shiningrush/droplet" "net/http" "os" "os/signal" "syscall" "time" + "github.com/shiningrush/droplet" + "github.com/apisix/manager-api/conf" "github.com/apisix/manager-api/internal" "github.com/apisix/manager-api/internal/core/storage" "github.com/apisix/manager-api/internal/core/store" + "github.com/apisix/manager-api/internal/handler" "github.com/apisix/manager-api/internal/utils" "github.com/apisix/manager-api/log" ) From 63b8647154bac408120b8a37b52f97fa3657a9f2 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Wed, 9 Dec 2020 16:39:20 +0800 Subject: [PATCH 4/9] chore: access log format --- api/filter/logging.go | 10 +++++----- api/internal/route.go | 2 +- api/log/zap.go | 3 +-- api/main.go | 2 +- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/api/filter/logging.go b/api/filter/logging.go index ee2ef7d1b5..dfc2938e9d 100644 --- a/api/filter/logging.go +++ b/api/filter/logging.go @@ -24,7 +24,6 @@ import ( "go.uber.org/zap" ) - func RequestLogHandler(logger *zap.SugaredLogger) gin.HandlerFunc { return func(c *gin.Context) { start, host, remoteIP, path, method := time.Now(), c.Request.Host, c.ClientIP(), c.Request.URL.Path, c.Request.Method @@ -43,14 +42,15 @@ func RequestLogHandler(logger *zap.SugaredLogger) gin.HandlerFunc { errs = append(errs, err.Error()) } - logger.Info(path, + logger.Desugar().Info(path, + //zap.String("path", path), + zap.Int("status", statusCode), + zap.String("host", host), + zap.String("query", query), zap.String("requestId", requestId), zap.Duration("latency", latency), zap.String("remoteIP", remoteIP), zap.String("method", method), - zap.Int("status", statusCode), - zap.String("host", host), - zap.String("query", query), //zap.String("respBody", respBody), zap.Strings("errs", errs), ) diff --git a/api/internal/route.go b/api/internal/route.go index 5b1b10646f..83a3e7282c 100644 --- a/api/internal/route.go +++ b/api/internal/route.go @@ -48,7 +48,7 @@ func SetUpRouter() *gin.Engine { logger := log.GetLogger(log.AccessLog) store := cookie.NewStore([]byte("secret")) r.Use(sessions.Sessions("session", store)) - r.Use(filter.CORS(), filter.RequestLogHandler(logger), filter.Authentication(), filter.RequestId(), filter.RecoverHandler()) + r.Use(filter.CORS(), filter.RequestId(), filter.RequestLogHandler(logger), filter.Authentication(), filter.RecoverHandler()) r.Use(static.Serve("/", static.LocalFile(conf.WebDir, false))) r.NoRoute(func(c *gin.Context) { c.File(fmt.Sprintf("%s/index.html", conf.WebDir)) diff --git a/api/log/zap.go b/api/log/zap.go index deb8de8fac..bd3807eb43 100644 --- a/api/log/zap.go +++ b/api/log/zap.go @@ -31,7 +31,7 @@ func init() { logger = GetLogger(ErrorLog) } -func GetLogger (logType Type) *zap.SugaredLogger{ +func GetLogger(logType Type) *zap.SugaredLogger { writeSyncer := fileWriter(logType) encoder := getEncoder() logLevel := getLogLevel() @@ -72,7 +72,6 @@ func getEncoder() zapcore.Encoder { return zapcore.NewConsoleEncoder(encoderConfig) } - func fileWriter(logType Type) zapcore.WriteSyncer { logPath := conf.ErrorLogPath if logType == AccessLog { diff --git a/api/main.go b/api/main.go index 88f2f0cd9b..a0b49bcf7e 100644 --- a/api/main.go +++ b/api/main.go @@ -24,7 +24,7 @@ import ( "os/signal" "syscall" "time" - + "github.com/shiningrush/droplet" "github.com/apisix/manager-api/conf" From 1629a2e018a81a70c0d2fec78bac4810940efec4 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Wed, 9 Dec 2020 16:48:39 +0800 Subject: [PATCH 5/9] test: add test case for access log --- api/conf/conf.yaml | 4 ++++ api/test/shell/cli_test.sh | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/api/conf/conf.yaml b/api/conf/conf.yaml index 7f147cbbb8..bf4a09dfcc 100644 --- a/api/conf/conf.yaml +++ b/api/conf/conf.yaml @@ -32,6 +32,10 @@ conf: file_path: logs/error.log # supports relative path, absolute path, standard output # such as: logs/error.log, /tmp/logs/error.log, /dev/stdout, /dev/stderr + access_log: + file_path: + logs/access.log # supports relative path, absolute path, standard output + # such as: logs/access.log, /tmp/logs/access.log, /dev/stdout, /dev/stderr authentication: secret: secret # secret for jwt token generation. diff --git a/api/test/shell/cli_test.sh b/api/test/shell/cli_test.sh index a4be250d82..b95e02d73c 100755 --- a/api/test/shell/cli_test.sh +++ b/api/test/shell/cli_test.sh @@ -95,6 +95,20 @@ if [[ `grep -c "INFO" ./error.log` -eq '0' ]]; then fi +# access log test +./manager-api & +sleep 3 + +curl http://127.0.0.1:9000/apisix/admin/user/login -d '{"username":"admin", "password": "admin"}' + +pkill -f manager-api + +if [[ `grep -c "/apisix/admin/user/login" ./logs/access.log` -eq '0' ]]; then + echo "failed: failed to write access log" + exit 1 +fi + + # etcd basic auth # add root user curl -L http://localhost:2379/v3/auth/user/add -d '{"name": "root", "password": "root"}' From aaf3e6a92276e8a3c5bde3901b4b52436617d89b Mon Sep 17 00:00:00 2001 From: nic-chen Date: Thu, 10 Dec 2020 16:34:05 +0800 Subject: [PATCH 6/9] chore: add access log example --- api/conf/conf.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/api/conf/conf.yaml b/api/conf/conf.yaml index bf4a09dfcc..802b11dc14 100644 --- a/api/conf/conf.yaml +++ b/api/conf/conf.yaml @@ -36,6 +36,7 @@ conf: file_path: logs/access.log # supports relative path, absolute path, standard output # such as: logs/access.log, /tmp/logs/access.log, /dev/stdout, /dev/stderr + # log example: 2020-12-09T16:38:09.039+0800 INFO filter/logging.go:46 /apisix/admin/routes/r1 {"status": 401, "host": "127.0.0.1:9000", "query": "asdfsafd=adf&a=a", "requestId": "3d50ecb8-758c-46d1-af5b-cd9d1c820156", "latency": 0, "remoteIP": "127.0.0.1", "method": "PUT", "errs": []} authentication: secret: secret # secret for jwt token generation. From 95482ad0c6aa22907db48f51c057413fec216549 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Thu, 10 Dec 2020 19:39:53 +0800 Subject: [PATCH 7/9] fix: according to review --- api/conf/conf.go | 5 ++--- api/filter/logging.go | 2 +- api/log/zap.go | 9 +++++++-- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/api/conf/conf.go b/api/conf/conf.go index a641132f3c..b34c339db6 100644 --- a/api/conf/conf.go +++ b/api/conf/conf.go @@ -71,7 +71,6 @@ type ErrorLog struct { } type AccessLog struct { - Level string FilePath string `yaml:"file_path"` } @@ -150,7 +149,7 @@ func setConf() { ErrorLogPath = config.Conf.Log.ErrorLog.FilePath } if !filepath.IsAbs(ErrorLogPath) { - ErrorLogPath, err = filepath.Abs(WorkDir + "/" + ErrorLogPath) + ErrorLogPath, err = filepath.Abs(filepath.Join(WorkDir, ErrorLogPath)) if err != nil { panic(err) } @@ -161,7 +160,7 @@ func setConf() { AccessLogPath = config.Conf.Log.AccessLog.FilePath } if !filepath.IsAbs(AccessLogPath) { - AccessLogPath, err = filepath.Abs(WorkDir + "/" + AccessLogPath) + AccessLogPath, err = filepath.Abs(filepath.Join(WorkDir, AccessLogPath)) if err != nil { panic(err) } diff --git a/api/filter/logging.go b/api/filter/logging.go index dfc2938e9d..0a01f6a42f 100644 --- a/api/filter/logging.go +++ b/api/filter/logging.go @@ -30,7 +30,7 @@ func RequestLogHandler(logger *zap.SugaredLogger) gin.HandlerFunc { query := c.Request.URL.RawQuery requestId := c.Writer.Header().Get("X-Request-Id") - blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer} + blw := &bodyLogWriter{body: bytes.NewBuffer(nil), ResponseWriter: c.Writer} c.Writer = blw c.Next() latency := time.Since(start) / 1000000 diff --git a/api/log/zap.go b/api/log/zap.go index bd3807eb43..87c384da91 100644 --- a/api/log/zap.go +++ b/api/log/zap.go @@ -33,7 +33,7 @@ func init() { func GetLogger(logType Type) *zap.SugaredLogger { writeSyncer := fileWriter(logType) - encoder := getEncoder() + encoder := getEncoder(logType) logLevel := getLogLevel() if logType == AccessLog { logLevel = zapcore.InfoLevel @@ -65,10 +65,15 @@ func getLogLevel() zapcore.LevelEnabler { return level } -func getEncoder() zapcore.Encoder { +func getEncoder(logType Type) zapcore.Encoder { encoderConfig := zap.NewProductionEncoderConfig() encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder + + if logType == AccessLog { + encoderConfig.LevelKey = zapcore.OmitKey + } + return zapcore.NewConsoleEncoder(encoderConfig) } From cf6cdcbcc878686f7de95b70339565420823b2f5 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Thu, 10 Dec 2020 21:16:59 +0800 Subject: [PATCH 8/9] test: add unit test for `logging` middleware --- api/filter/logging_test.go | 46 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 api/filter/logging_test.go diff --git a/api/filter/logging_test.go b/api/filter/logging_test.go new file mode 100644 index 0000000000..3a374d4071 --- /dev/null +++ b/api/filter/logging_test.go @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package filter + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + + "github.com/apisix/manager-api/log" +) + +func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, nil) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +func TestRequestLogHandler(t *testing.T) { + r := gin.New() + logger := log.GetLogger(log.AccessLog) + r.Use(RequestLogHandler(logger)) + r.GET("/", func(c *gin.Context) { + }) + + w := performRequest(r, "GET", "/") + assert.Equal(t, 200, w.Code) +} \ No newline at end of file From 45129f89bf9e32735b6c6f313b66df29276d56c6 Mon Sep 17 00:00:00 2001 From: nic-chen Date: Thu, 10 Dec 2020 23:13:08 +0800 Subject: [PATCH 9/9] fix: license checker CI failed --- api/filter/logging_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/filter/logging_test.go b/api/filter/logging_test.go index 3a374d4071..087d8b0e85 100644 --- a/api/filter/logging_test.go +++ b/api/filter/logging_test.go @@ -43,4 +43,4 @@ func TestRequestLogHandler(t *testing.T) { w := performRequest(r, "GET", "/") assert.Equal(t, 200, w.Code) -} \ No newline at end of file +}