From 022c100dc996496df6362f9c6e5aae833f199328 Mon Sep 17 00:00:00 2001 From: chenquan Date: Tue, 12 Oct 2021 21:50:30 +0800 Subject: [PATCH] Add request method in http log (#1120) * Add request method in http log * Update log format --- rest/handler/loghandler.go | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/rest/handler/loghandler.go b/rest/handler/loghandler.go index 9aaa560c..fd8adb2f 100644 --- a/rest/handler/loghandler.go +++ b/rest/handler/loghandler.go @@ -152,11 +152,12 @@ func dumpRequest(r *http.Request) string { func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *internal.LogCollector) { var buf bytes.Buffer duration := timer.Duration() - buf.WriteString(fmt.Sprintf("%d - %s - %s - %s - %s", - code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(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))) if duration > slowThreshold { - logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - %s - %s - slowcall(%s)", - code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)) + logger.Slowf("[HTTP] %s - %d - %s - %s - %s - slowcall(%s)", + r.Method, code, r.RequestURI, httpx.GetRemoteAddr(r), r.UserAgent(), timex.ReprOfDuration(duration)) } ok := isOkResponse(code) @@ -177,9 +178,9 @@ func logBrief(r *http.Request, code int, timer *utils.ElapsedTimer, logs *intern } if ok { - logx.WithContext(r.Context()).Info(buf.String()) + logger.Info(buf.String()) } else { - logx.WithContext(r.Context()).Error(buf.String()) + logger.Error(buf.String()) } } @@ -187,11 +188,12 @@ func logDetails(r *http.Request, response *detailLoggedResponseWriter, timer *ut logs *internal.LogCollector) { 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))) + 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))) if duration > slowThreshold { - logx.WithContext(r.Context()).Slowf("[HTTP] %d - %s - slowcall(%s)\n=> %s\n", - response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)) + logger.Slowf("[HTTP] %s - %d - %s - slowcall(%s)\n=> %s\n", + r.Method, response.writer.code, r.RemoteAddr, timex.ReprOfDuration(duration), dumpRequest(r)) } body := logs.Flush() @@ -204,7 +206,7 @@ func logDetails(r *http.Request, response *detailLoggedResponseWriter, timer *ut buf.WriteString(fmt.Sprintf("<= %s", respBuf)) } - logx.WithContext(r.Context()).Info(buf.String()) + logger.Info(buf.String()) } func isOkResponse(code int) bool {