You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/rest/handler/loghandler.go

216 lines
5.6 KiB
Go

4 years ago
package handler
4 years ago
import (
"bufio"
4 years ago
"bytes"
"context"
"errors"
4 years ago
"fmt"
"io"
3 years ago
"io/ioutil"
"net"
4 years ago
"net/http"
"net/http/httputil"
3 years ago
"strings"
4 years ago
"time"
"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"
"github.com/tal-tech/go-zero/rest/httpx"
"github.com/tal-tech/go-zero/rest/internal"
4 years ago
)
3 years ago
const (
limitBodyBytes = 1024
slowThreshold = time.Millisecond * 500
)
4 years ago
type loggedResponseWriter struct {
4 years ago
w http.ResponseWriter
r *http.Request
code int
}
func (w *loggedResponseWriter) Flush() {
if flusher, ok := w.w.(http.Flusher); ok {
flusher.Flush()
}
}
func (w *loggedResponseWriter) Header() http.Header {
4 years ago
return w.w.Header()
}
// 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) {
if hijacked, ok := w.w.(http.Hijacker); ok {
return hijacked.Hijack()
}
return nil, nil, errors.New("server doesn't support hijacking")
}
func (w *loggedResponseWriter) Write(bytes []byte) (int, error) {
4 years ago
return w.w.Write(bytes)
}
func (w *loggedResponseWriter) WriteHeader(code int) {
4 years ago
w.w.WriteHeader(code)
w.code = code
}
// LogHandler returns a middleware that logs http request and response.
4 years ago
func LogHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := utils.NewElapsedTimer()
4 years ago
logs := new(internal.LogCollector)
lrw := loggedResponseWriter{
4 years ago
w: w,
r: r,
code: http.StatusOK,
}
var dup io.ReadCloser
r.Body, dup = iox.DupReadCloser(r.Body)
4 years ago
next.ServeHTTP(&lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
4 years ago
r.Body = dup
logBrief(r, lrw.code, timer, logs)
})
}
type detailLoggedResponseWriter struct {
writer *loggedResponseWriter
4 years ago
buf *bytes.Buffer
}
func newDetailLoggedResponseWriter(writer *loggedResponseWriter, buf *bytes.Buffer) *detailLoggedResponseWriter {
return &detailLoggedResponseWriter{
4 years ago
writer: writer,
buf: buf,
}
}
func (w *detailLoggedResponseWriter) Flush() {
w.writer.Flush()
}
func (w *detailLoggedResponseWriter) Header() http.Header {
4 years ago
return w.writer.Header()
}
// 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")
}
func (w *detailLoggedResponseWriter) Write(bs []byte) (int, error) {
4 years ago
w.buf.Write(bs)
return w.writer.Write(bs)
}
func (w *detailLoggedResponseWriter) WriteHeader(code int) {
4 years ago
w.writer.WriteHeader(code)
}
// DetailedLogHandler returns a middleware that logs http request and response in details.
4 years ago
func DetailedLogHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
timer := utils.NewElapsedTimer()
var buf bytes.Buffer
lrw := newDetailLoggedResponseWriter(&loggedResponseWriter{
4 years ago
w: w,
r: r,
code: http.StatusOK,
}, &buf)
var dup io.ReadCloser
r.Body, dup = iox.DupReadCloser(r.Body)
4 years ago
logs := new(internal.LogCollector)
next.ServeHTTP(lrw, r.WithContext(context.WithValue(r.Context(), internal.LogContext, logs)))
4 years ago
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()
}
return string(reqContent)
4 years ago
}
4 years ago
func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) {
4 years ago
var buf bytes.Buffer
duration := timer.Duration()
logger := logx.WithContext(r.Context())
buf.WriteString(fmt.Sprintf("[HTTP] %s - %d - %s - %s - %s - %s",
r.Method, code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)))
4 years ago
if duration > slowThreshold {
logger.Slowf("[HTTP] %s - %d - %s - %s - %s - slowcall(%s)",
r.Method, code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration))
4 years ago
}
ok := isOkResponse(code)
if !ok {
3 years ago
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)))
}
4 years ago
}
body := logs.Flush()
if len(body) > 0 {
buf.WriteString(fmt.Sprintf("\n%s", body))
}
if ok {
logger.Info(buf.String())
4 years ago
} else {
logger.Error(buf.String())
4 years ago
}
}
func logDetails(r *http.Request, response *detailLoggedResponseWriter, timer *utils.ElapsedTimer,
4 years ago
logs *internal.LogCollector) {
4 years ago
var buf bytes.Buffer
duration := timer.Duration()
logger := logx.WithContext(r.Context())
buf.WriteString(fmt.Sprintf("[HTTP] %s - %d - %s - %s\n=> %s\n",
r.Method, response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)))
4 years ago
if duration > slowThreshold {
logger.Slowf("[HTTP] %s - %d - %s - slowcall(%s)\n=> %s\n",
r.Method, response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r))
4 years ago
}
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))
}
logger.Info(buf.String())
4 years ago
}
func isOkResponse(code int) bool {
// not server error
return code < http.StatusInternalServerError
}