88 "fmt"
99 "log/slog"
1010 "net/http"
11+ "os"
1112 "strconv"
1213 "strings"
1314 "time"
2728// Logger will read existing and write new logging.Fields available in current context.
2829// See `ExtractFields` and `InjectFields` for details.
2930func HttpInterceptor (l logging.Logger ) func (handler http.Handler ) http.Handler {
31+ var logHttpHeader bool
32+ {
33+ vHeader := os .Getenv ("HTTP_GO_LOG_HTTP_HEADER" )
34+ if vh , err := strconv .ParseBool (vHeader ); err == nil {
35+ logHttpHeader = vh
36+ }
37+ }
38+
3039 return func (handler http.Handler ) http.Handler {
3140 return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
3241 var cost time_.Cost
@@ -35,16 +44,28 @@ func HttpInterceptor(l logging.Logger) func(handler http.Handler) http.Handler {
3544 attrs = append (attrs , slog .String (SystemTag [0 ], SystemTag [1 ]))
3645 attrs = append (attrs , slog .Time ("http.start_time" , time .Now ()))
3746 attrs = append (attrs , extractLoggingFieldsFromHttpRequest (r )... )
38- l .Log (r .Context (), logging .LevelInfo , fmt .Sprintf ("http request received" ), attrs ... )
47+
48+ var reqAttrs = attrs
49+ if logHttpHeader {
50+ reqAttrs = append (reqAttrs , httpHeaderToAttr (r .Header , "http.request.header" ))
51+ }
52+ l .Log (r .Context (), logging .LevelInfo , fmt .Sprintf ("http request received" ), reqAttrs ... )
3953
4054 rw := http_ .NewResponseWriterDelegator (w )
4155 handler .ServeHTTP (rw , r )
4256
43- attrs = append (attrs , slog .String ("http.status_code" , slices_ .FirstOrZero (http .StatusText (rw .Status ()), "CODE(" + strconv .FormatInt (int64 (rw .Status ()), 10 )+ ")" )),
57+ attrs = append (attrs ,
58+ slog .String ("http.status_code" , slices_ .FirstOrZero (http .StatusText (rw .Status ()), "CODE(" + strconv .FormatInt (int64 (rw .Status ()), 10 )+ ")" )),
4459 slog .Duration ("cost" , cost .Elapse ()),
4560 slog .Int64 ("http.request_body_size" , r .ContentLength ),
4661 slog .Int64 ("http.response_body_size" , rw .Written ()))
47- l .Log (r .Context (), logging .LevelInfo , fmt .Sprintf ("finished http call with code %d" , rw .Status ()), attrs ... )
62+
63+ var respAttrs = attrs
64+ if logHttpHeader {
65+ respAttrs = append (respAttrs , httpHeaderToAttr (r .Header , "http.response.header" ))
66+ }
67+ l .Log (r .Context (), logging .LevelInfo , fmt .Sprintf ("finished http call with status code %d" , rw .Status ()),
68+ respAttrs ... )
4869 })
4970 }
5071}
@@ -76,3 +97,11 @@ func extractLoggingFieldsFromHttpRequest(r *http.Request) []any {
7697 }
7798 return attrs
7899}
100+
101+ func httpHeaderToAttr (h http.Header , k string ) slog.Attr {
102+ var attrs []slog.Attr
103+ for k , v := range h {
104+ attrs = append (attrs , slog .Any (k , v ))
105+ }
106+ return slog .GroupAttrs (k , attrs ... )
107+ }
0 commit comments