-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
105 lines (86 loc) · 3.04 KB
/
logger.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Copyright (c) Liam Stanley <[email protected]>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.
package chix
import (
"net/http"
"sync/atomic"
"time"
"github.com/apex/log"
"github.com/go-chi/chi/v5/middleware"
)
// LogHandler is a function type that can be used to add any additional
// custom fields to a request log entry.
type LogHandler func(r *http.Request) M
var logHandlers atomic.Value // []LogHandler
// AddLogHandler can be used to inject additional metadata/fields into the
// log context. Use this to add things like authentication information, or
// similar, to the log entry.
//
// NOTE: the request context will only include entries that were registered
// in the request context prior to the structured logger being loaded.
func AddLogHandler(h LogHandler) {
handlers, ok := logHandlers.Load().([]LogHandler)
if !ok {
handlers = []LogHandler{}
}
handlers = append(handlers, h)
logHandlers.Store(handlers)
}
// UseStructuredLogger wraps each request and writes a log entry with
// extra info. UseStructuredLogger also injects a logger into the request
// context that can be used by children middleware business logic.
func UseStructuredLogger(logger log.Interface) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
bfields := log.Fields{}
bfields["src"] = "http"
// RequestID middleware must be loaded before this is loaded into
// the chain.
if id := middleware.GetReqID(r.Context()); id != "" {
bfields["rid"] = id
}
if ray := r.Header.Get("CF-Ray"); ray != "" {
bfields["ray_id"] = ray
}
if country := r.Header.Get("CF-IPCountry"); country != "" {
bfields["country"] = country
}
wrappedWriter := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
bfields["ip"] = r.RemoteAddr
bfields["host"] = r.Host
bfields["proto"] = r.Proto
bfields["method"] = r.Method
bfields["ua"] = r.Header.Get("User-Agent")
bfields["bytes_in"] = r.Header.Get("Content-Length")
logEntry := logger.WithFields(bfields)
start := time.Now()
defer func() {
finish := time.Since(start)
// If log handlers were provided, and they returned a map,
// then we'll use that to add additional fields to the log
// context.
if handlers, ok := logHandlers.Load().([]LogHandler); ok {
var fields M
for _, fn := range handlers {
if fields = fn(r); fields != nil {
logEntry = logEntry.WithFields(fields)
}
}
}
logEntry.WithFields(log.Fields{
"code": wrappedWriter.Status(),
"duration_ms": finish.Milliseconds(),
"bytes_out": wrappedWriter.BytesWritten(),
}).Info(r.URL.RequestURI())
}()
next.ServeHTTP(wrappedWriter, r.WithContext(log.NewContext(r.Context(), logEntry)))
}
return http.HandlerFunc(fn)
}
}
// Log is a helper for obtaining the structured logger from the request
// context.
func Log(r *http.Request) log.Interface {
return log.FromContext(r.Context())
}