go-zero/rest/handler/loghandler.go

229 lines
5.9 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"
2021-03-15 20:11:09 +08:00
"errors"
2020-07-26 17:09:05 +08:00
"fmt"
"io"
2021-08-22 23:36:35 +08:00
"io/ioutil"
2021-03-09 21:30:45 +08:00
"net"
2020-07-26 17:09:05 +08:00
"net/http"
"net/http/httputil"
2021-08-22 23:36:35 +08:00
"strings"
2020-07-26 17:09:05 +08:00
"time"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/timex"
"github.com/zeromicro/go-zero/core/utils"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal"
2020-07-26 17:09:05 +08:00
)
2021-08-22 23:36:35 +08:00
const (
limitBodyBytes = 1024
defaultSlowThreshold = time.Millisecond * 500
2021-08-22 23:36:35 +08:00
)
2020-07-26 17:09:05 +08:00
var slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold)
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) {
2021-03-15 20:11:09 +08:00
if hijacked, ok := w.w.(http.Hijacker); ok {
return hijacked.Hijack()
}
return nil, nil, errors.New("server doesn't support hijacking")
2021-03-09 21:30:45 +08:00
}
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-15 20:11:09 +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 *detailLoggedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacked, ok := w.writer.w.(http.Hijacker); ok {
return hijacked.Hijack()
}
return nil, nil, errors.New("server doesn't support hijacking")
}
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)
})
}
// SetSlowThreshold sets the slow threshold.
func SetSlowThreshold(threshold time.Duration) {
slowThreshold.Set(threshold)
}
2020-07-26 17:09:05 +08:00
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()
logger := logx.WithContext(r.Context()).WithDuration(duration)
buf.WriteString(fmt.Sprintf("[HTTP] %s - %d - %s - %s - %s",
r.Method, code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent()))
if duration > slowThreshold.Load() {
logger.Slowf("[HTTP] %s - %d - %s - %s - %s - slowcall(%s)",
r.Method, code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration))
2020-07-26 17:09:05 +08:00
}
ok := isOkResponse(code)
if !ok {
2021-08-22 23:36:35 +08:00
fullReq := dumpRequest(r)
limitReader := io.LimitReader(strings.NewReader(fullReq), limitBodyBytes)
body, err := ioutil.ReadAll(limitReader)
if err != nil {
buf.WriteString(fmt.Sprintf("\n%s", fullReq))
} else {
buf.WriteString(fmt.Sprintf("\n%s", string(body)))
}
2020-07-26 17:09:05 +08:00
}
body := logs.Flush()
if len(body) > 0 {
buf.WriteString(fmt.Sprintf("\n%s", body))
}
if ok {
logger.Info(buf.String())
2020-07-26 17:09:05 +08:00
} else {
logger.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()
code := response.writer.code
logger := logx.WithContext(r.Context())
buf.WriteString(fmt.Sprintf("[HTTP] %s - %d - %s - %s\n=> %s\n",
r.Method, code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)))
if duration > defaultSlowThreshold {
logger.Slowf("[HTTP] %s - %d - %s - slowcall(%s)\n=> %s\n",
r.Method, code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))
2020-07-26 17:09:05 +08:00
}
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))
}
if isOkResponse(code) {
logger.Info(buf.String())
} else {
logger.Error(buf.String())
}
2020-07-26 17:09:05 +08:00
}
func isOkResponse(code int) bool {
// not server error
return code < http.StatusInternalServerError
}