go-zero/rest/handler/loghandler.go

187 lines
4.8 KiB
Go
Raw Normal View History

2020-07-29 18:00:04 +08:00
package handler
2020-07-26 17:09:05 +08:00
import (
2021-03-09 21:30:45 +08:00
"bufio"
2020-07-26 17:09:05 +08:00
"bytes"
"context"
"fmt"
"io"
2021-03-09 21:30:45 +08:00
"net"
2020-07-26 17:09:05 +08:00
"net/http"
"net/http/httputil"
"time"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/iox"
"github.com/tal-tech/go-zero/core/logx"
"github.com/tal-tech/go-zero/core/timex"
"github.com/tal-tech/go-zero/core/utils"
2020-08-12 12:25:52 +08:00
"github.com/tal-tech/go-zero/rest/httpx"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/rest/internal"
2020-07-26 17:09:05 +08:00
)
const slowThreshold = time.Millisecond * 500
2021-03-01 19:15:35 +08:00
type loggedResponseWriter struct {
2020-07-26 17:09:05 +08:00
w http.ResponseWriter
r *http.Request
code int
}
2021-03-09 21:30:45 +08:00
func (w *loggedResponseWriter) Flush() {
if flusher, ok := w.w.(http.Flusher); ok {
flusher.Flush()
}
}
2021-03-01 19:15:35 +08:00
func (w *loggedResponseWriter) Header() http.Header {
2020-07-26 17:09:05 +08:00
return w.w.Header()
}
2021-03-09 21:30:45 +08:00
// Hijack implements the http.Hijacker interface.
// This expands the Response to fulfill http.Hijacker if the underlying http.ResponseWriter supports it.
func (w *loggedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.w.(http.Hijacker).Hijack()
}
2021-03-01 19:15:35 +08:00
func (w *loggedResponseWriter) Write(bytes []byte) (int, error) {
2020-07-26 17:09:05 +08:00
return w.w.Write(bytes)
}
2021-03-01 19:15:35 +08:00
func (w *loggedResponseWriter) WriteHeader(code int) {
2020-07-26 17:09:05 +08:00
w.w.WriteHeader(code)
w.code = code
}
2021-03-01 19:15:35 +08:00
// LogHandler returns a middleware that logs http request and response.
2020-07-26 17:09:05 +08:00
func LogHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := utils.NewElapsedTimer()
2020-07-29 18:00:04 +08:00
logs := new(internal.LogCollector)
2021-03-01 19:15:35 +08:00
lrw := loggedResponseWriter{
2020-07-26 17:09:05 +08:00
w: w,
r: r,
code: http.StatusOK,
}
var dup io.ReadCloser
r.Body, dup = iox.DupReadCloser(r.Body)
2020-07-29 18:00:04 +08:00
next.ServeHTTP(&lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
2020-07-26 17:09:05 +08:00
r.Body = dup
logBrief(r, lrw.code, timer, logs)
})
}
2021-03-01 19:15:35 +08:00
type detailLoggedResponseWriter struct {
writer *loggedResponseWriter
2020-07-26 17:09:05 +08:00
buf *bytes.Buffer
}
2021-03-01 19:15:35 +08:00
func newDetailLoggedResponseWriter(writer *loggedResponseWriter, buf *bytes.Buffer) *detailLoggedResponseWriter {
return &detailLoggedResponseWriter{
2020-07-26 17:09:05 +08:00
writer: writer,
buf: buf,
}
}
2021-03-01 19:15:35 +08:00
func (w *detailLoggedResponseWriter) Flush() {
w.writer.Flush()
}
2021-03-01 19:15:35 +08:00
func (w *detailLoggedResponseWriter) Header() http.Header {
2020-07-26 17:09:05 +08:00
return w.writer.Header()
}
2021-03-01 19:15:35 +08:00
func (w *detailLoggedResponseWriter) Write(bs []byte) (int, error) {
2020-07-26 17:09:05 +08:00
w.buf.Write(bs)
return w.writer.Write(bs)
}
2021-03-01 19:15:35 +08:00
func (w *detailLoggedResponseWriter) WriteHeader(code int) {
2020-07-26 17:09:05 +08:00
w.writer.WriteHeader(code)
}
2021-03-01 19:15:35 +08:00
// DetailedLogHandler returns a middleware that logs http request and response in details.
2020-07-26 17:09:05 +08:00
func DetailedLogHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := utils.NewElapsedTimer()
var buf bytes.Buffer
2021-03-01 19:15:35 +08:00
lrw := newDetailLoggedResponseWriter(&loggedResponseWriter{
2020-07-26 17:09:05 +08:00
w: w,
r: r,
code: http.StatusOK,
}, &buf)
var dup io.ReadCloser
r.Body, dup = iox.DupReadCloser(r.Body)
2020-07-29 18:00:04 +08:00
logs := new(internal.LogCollector)
next.ServeHTTP(lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
2020-07-26 17:09:05 +08:00
r.Body = dup
logDetails(r, lrw, timer, logs)
})
}
func dumpRequest(r *http.Request) string {
reqContent, err := httputil.DumpRequest(r, true)
if err != nil {
return err.Error()
}
2021-02-09 13:50:21 +08:00
return string(reqContent)
2020-07-26 17:09:05 +08:00
}
2020-07-29 18:00:04 +08:00
func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) {
2020-07-26 17:09:05 +08:00
var buf bytes.Buffer
duration := timer.Duration()
buf.WriteString(fmt.Sprintf("%d - %s - %s - %s - %s",
2020-08-12 12:25:52 +08:00
code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)))
2020-07-26 17:09:05 +08:00
if duration > slowThreshold {
2020-09-20 22:02:45 +08:00
logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - %s - %s - slowcall(%s)",
2020-08-12 12:25:52 +08:00
code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration))
2020-07-26 17:09:05 +08:00
}
ok := isOkResponse(code)
if !ok {
buf.WriteString(fmt.Sprintf("\n%s", dumpRequest(r)))
}
body := logs.Flush()
if len(body) > 0 {
buf.WriteString(fmt.Sprintf("\n%s", body))
}
if ok {
2020-09-20 22:02:45 +08:00
logx.WithContext(r.Context()).Info(buf.String())
2020-07-26 17:09:05 +08:00
} else {
2020-09-20 22:02:45 +08:00
logx.WithContext(r.Context()).Error(buf.String())
2020-07-26 17:09:05 +08:00
}
}
2021-03-01 19:15:35 +08:00
func logDetails(r *http.Request, response *detailLoggedResponseWriter, timer *utils.ElapsedTimer,
2020-07-29 18:00:04 +08:00
logs *internal.LogCollector) {
2020-07-26 17:09:05 +08:00
var buf bytes.Buffer
duration := timer.Duration()
buf.WriteString(fmt.Sprintf("%d - %s - %s\n=> %s\n",
response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)))
if duration > slowThreshold {
2020-09-20 22:02:45 +08:00
logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - slowcall(%s)\n=> %s\n",
2020-07-26 17:09:05 +08:00
response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))
}
body := logs.Flush()
if len(body) > 0 {
buf.WriteString(fmt.Sprintf("%s\n", body))
}
respBuf := response.buf.Bytes()
if len(respBuf) > 0 {
buf.WriteString(fmt.Sprintf("<= %s", respBuf))
}
2020-09-20 22:02:45 +08:00
logx.WithContext(r.Context()).Info(buf.String())
2020-07-26 17:09:05 +08:00
}
func isOkResponse(code int) bool {
// not server error
return code < http.StatusInternalServerError
}