-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
44 lines (39 loc) · 1.24 KB
/
log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package httpserver
import (
"bufio"
"io"
"net/http"
"time"
)
// buffer memory to store log before writing them into writer/file
type buffer chan []byte
// Write overwrite io.Writer Write method to instead of writing directly into file,
// it passes the bytes into buffer memory to be written into actual writer/file asynchronously.
func (b buffer) Write(p []byte) (int, error) {
b <- append(([]byte)(nil), p...)
return len(p), nil
}
// worker to write log data from buffer memory into writer/file asynchronously.
func write(b buffer, w io.Writer) {
writer := bufio.NewWriter(w)
for p := range b {
writer.Write(p)
writer.Flush()
}
}
// middleware for log
func (s *Server) log(next http.HandlerFunc, params ...interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next(w, r)
elapsed := time.Since(start)
var statusCode int
rw, ok := w.(*responseWriter)
if !ok { // impossible...!!! but let be safe.
statusCode = http.StatusOK // default http.ResponseWriter status code
} else {
statusCode = rw.statusCode
}
s.logger.Printf("%s | httpserver | %s | %d | %s | %v | %s\n", time.Now().Format(time.RFC3339), r.Method, statusCode, r.URL.Path, elapsed, r.Header.Get("Request-Id"))
}
}