加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
requestlogger.go 1.13 KB
一键复制 编辑 原始数据 按行查看 历史
henrylee2cn 提交于 2016-04-08 12:43 . 更新一些变量名
package lessgo
import (
"net"
"time"
"github.com/lessgo/lessgo/logs"
"github.com/lessgo/lessgo/logs/color"
)
// RequestLogger returns a middleware that logs HTTP requests.
func RequestLogger() MiddlewareFunc {
return func(next HandlerFunc) HandlerFunc {
return func(c Context) (err error) {
req := c.Request()
res := c.Response()
remoteAddr := req.RemoteAddress()
if ip := req.Header().Get(HeaderXRealIP); ip != "" {
remoteAddr = ip
} else if ip = req.Header().Get(HeaderXForwardedFor); ip != "" {
remoteAddr = ip
} else {
remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
}
start := time.Now()
if err := next(c); err != nil {
c.Error(err)
}
stop := time.Now()
method := req.Method()
path := req.URL().Path()
if path == "" {
path = "/"
}
size := res.Size()
n := res.Status()
code := color.Green(n)
switch {
case n >= 500:
code = color.Red(n)
case n >= 400:
code = color.Yellow(n)
case n >= 300:
code = color.Cyan(n)
}
logs.Debug("%s | %s | %s | %s | %s | %d", remoteAddr, method, path, code, stop.Sub(start), size)
return nil
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化