mirror of
https://gitee.com/johng/gf
synced 2026-07-08 14:39:50 +08:00
ghttp.Server 日志功能完善
This commit is contained in:
@ -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)
|
||||
}
|
||||
|
||||
|
||||
@ -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)
|
||||
}
|
||||
|
||||
@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user