github.com/go-kivik/kivik/v4@v4.3.2/x/kivikd/logger.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 //go:build !js 14 15 package kivikd 16 17 import ( 18 "net/http" 19 "time" 20 21 "github.com/go-kivik/kivik/v4/x/kivikd/logger" 22 ) 23 24 type statusWriter struct { 25 http.ResponseWriter 26 status int 27 byteCount int 28 } 29 30 func (w *statusWriter) WriteHeader(status int) { 31 w.status = status 32 w.ResponseWriter.WriteHeader(status) 33 } 34 35 func (w *statusWriter) Write(b []byte) (int, error) { 36 n, err := w.ResponseWriter.Write(b) 37 w.byteCount += n 38 return n, err 39 } 40 41 func loggerMiddleware(rlog logger.RequestLogger) func(http.Handler) http.Handler { 42 return func(next http.Handler) http.Handler { 43 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 44 start := time.Now() 45 sw := &statusWriter{ResponseWriter: w} 46 next.ServeHTTP(sw, r) 47 session := MustGetSession(r.Context()) 48 var username string 49 if session.User != nil { 50 username = session.User.Name 51 } 52 fields := logger.Fields{ 53 logger.FieldUsername: username, 54 logger.FieldTimestamp: start, 55 logger.FieldElapsedTime: time.Since(start), 56 logger.FieldResponseSize: sw.byteCount, 57 } 58 rlog.Log(r, sw.status, fields) 59 }) 60 } 61 }