/**
* Author: zhanggaoyuancn@163.com
* Date: 2019-06-04
* Time: 14:54
* Software: GoLand
*/
package middleware
import (
"bytes"
"io/ioutil"
"net/http"
"time"
"xxx/app/pkg/logger"
"xxx/app/util"
"github.com/kataras/iris"
)
// LoggerMiddleware 日誌中介軟體
func LoggerMiddleware(ctx iris.Context) {
p := ctx.Request().URL.Path
method := ctx.Request().Method
start := time.Now()
fields := make(map[string]interface{})
fields["title"] = "訪問日誌"
fields["fun_name"] = JoinRouter(method, p)
fields["ip"] = util.GetCilentIp(ctx.Request())
fields["method"] = method
fields["url"] = ctx.Request().URL.String()
fields["proto"] = ctx.Request().Proto
fields["header"] = ctx.Request().Header
fields["user_agent"] = ctx.Request().UserAgent()
fields["x_request_id"] = ctx.GetHeader("X-Request-Id")
// 如果是POST/PUT請求,並且內容型別為JSON,則讀取內容體
if method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch {
body, err := ioutil.ReadAll(ctx.Request().Body)
if err == nil {
defer ctx.Request().Body.Close()
buf := bytes.NewBuffer(body)
ctx.Request().Body = ioutil.NopCloser(buf)
fields["content_length"] = ctx.GetContentLength()
fields["body"] = string(body)
}
}
ctx.Next()
//下面是返回日誌
fields["res_status"] = ctx.ResponseWriter().StatusCode()
if ctx.Values().GetString("out_err") != "" {
fields["out_err"] = ctx.Values().GetString("out_err")
}
fields["res_length"] = ctx.ResponseWriter().Header().Get("size")
if v := ctx.Values().Get("res_body"); v != nil {
if b, ok := v.([]byte); ok {
fields["res_body"] = string(b)
}
}
fields["uid"] = ctx.Values().GetString("uid")
timeConsuming := time.Since(start).Nanoseconds() / 1e6
logger.WithFields(fields).Infof("[http] %s-%s-%s-%d(%dms)",
p, ctx.Request().Method, util.GetCilentIp(ctx.Request()), ctx.ResponseWriter().StatusCode(), timeConsuming)
}
整個請求資料都有了。方便除錯