ghttp.Server 日志功能完善

This commit is contained in:
John
2018-04-20 18:52:04 +08:00
parent e42bbb46f9
commit 0b6dbf524e
3 changed files with 17 additions and 8 deletions

View File

@ -26,20 +26,20 @@ type Response struct {
// 自定义的ResponseWriter用于写入流的控制
type ResponseWriter struct {
http.ResponseWriter
status int // http status
length int // response length
Status int // http status
Length int // response length
}
// 覆盖父级的WriteHeader方法
func (w *ResponseWriter) Write(buffer []byte) (int, error) {
n, e := w.ResponseWriter.Write(buffer)
w.length += n
w.Length += n
return n, e
}
// 覆盖父级的WriteHeader方法
func (w *ResponseWriter) WriteHeader(code int) {
w.status = code
w.Status = code
w.ResponseWriter.WriteHeader(code)
}

View File

@ -23,7 +23,7 @@ func (s *Server) handleAccessLog(r *Request) {
v(r)
return
}
content := fmt.Sprintf(`"%s %s %s %s" %s %s`, r.Method, r.Host, r.URL.String(), r.Proto, gconv.String(r.Response.status), gconv.String(r.Response.length))
content := fmt.Sprintf(`"%s %s %s %s" %s %s`, r.Method, r.Host, r.URL.String(), r.Proto, gconv.String(r.Response.Status), gconv.String(r.Response.Length))
content += fmt.Sprintf(`, %s, "%s", "%s"`, r.GetClientIp(), r.Referer(), r.UserAgent())
s.accessLogger.Println(content)
}

View File

@ -1,17 +1,26 @@
package main
import (
"fmt"
"net/http"
"gitee.com/johng/gf/g/net/ghttp"
)
func main() {
s := ghttp.GetServer()
s.BindHandler("/log/test", func(r *ghttp.Request){
r.Response.Writeln("哈喽世界!")
s.BindHandler("/log/handler", func(r *ghttp.Request){
r.Response.WriteStatus(http.StatusNotFound, "文件找不到了")
})
s.SetLogPath("/tmp/gf.log")
s.SetAccessLogEnabled(true)
s.SetErrorLogEnabled(true)
s.SetLogHandler(func(r *ghttp.Request, error ...interface{}) {
if len(error) > 0 {
// 如果是错误日志
fmt.Println("错误产生了:", error[0])
}
// 这里是请求日志
fmt.Println("请求处理完成,请求地址:", r.URL.String(), "请求结果:", r.Response.Status)
})
s.SetPort(8199)
s.Run()
}