iris 系列文章 封装 请求日志

/**
* 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)
}

整个请求数据都有了。方便调试

本作品采用《CC 协议》,转载必须注明作者和本文链接
by JeffreyBool blog :point_right: link
JeffreyBool
讨论数量: 1

请问有一个完整的 iris web 项目么?想参考学习

3年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!