This repository has been archived by the owner on Jun 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
168 lines (141 loc) · 4.09 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
// logger.go
//
// Author:: Chirantan Mitra
// Copyright:: Copyright (c) 2015-2017. All rights reserved
// License:: MIT
// Parts of the logging.go are based on
// https://github.com/gorilla/handlers/blob/master/handlers.go
// gorilla/handlers is released under the BSD license.
// Copyright 2013 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"time"
)
// Logger implements methods that log in JSON format.
type Logger struct {
w io.Writer
}
// NewLogger creates an instance of Logger.
func NewLogger(w io.Writer) *Logger {
return &Logger{w: w}
}
func (logger Logger) Print(msg string) {
out := fmt.Sprintf(`{"time": %q, "msg": %q}
`, time.Now().Format("2006-01-02 15:04:05.999 Z07:00"), msg)
logger.w.Write([]byte(out))
}
func (logger Logger) Printf(format string, args ...interface{}) {
logger.Print(fmt.Sprintf(format, args...))
}
func (logger Logger) Fatal(msg string) {
logger.Print(msg)
os.Exit(1)
}
func (logger Logger) Fatalf(format string, args ...interface{}) {
logger.Printf(format, args...)
os.Exit(1)
}
// LoggingHandler wraps a http.Handler implementation with logging support.
type LoggingHandler struct {
writer io.Writer
handler http.Handler
}
// NewLoggingHandler return a http.Handler that wraps h and logs requests to out in
// JSON log Format.
func NewLoggingHandler(out io.Writer, h http.Handler) http.Handler {
return LoggingHandler{out, h}
}
func (h LoggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
startTime := time.Now()
logger := NewResponseLogger(w)
url := *req.URL
h.handler.ServeHTTP(logger, req)
logEntry := NewLogEntry(req, url, startTime, logger.Status(), logger.Size())
io.WriteString(h.writer, logEntry.Output())
}
// ResponseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP
// status code and body size.
type ResponseLogger struct {
w http.ResponseWriter
status int
size int
}
// NewResponseLogger returns an instance of ResponseLogger.
func NewResponseLogger(w http.ResponseWriter) *ResponseLogger {
return &ResponseLogger{w: w}
}
func (l *ResponseLogger) Header() http.Header {
return l.w.Header()
}
func (l *ResponseLogger) Write(b []byte) (int, error) {
if l.status == 0 {
// The status will be StatusOK if WriteHeader has not been called yet.
l.status = http.StatusOK
}
size, err := l.w.Write(b)
l.size += size
return size, err
}
func (l *ResponseLogger) WriteHeader(s int) {
l.w.WriteHeader(s)
l.status = s
}
func (l *ResponseLogger) Status() int {
return l.status
}
func (l *ResponseLogger) Size() int {
return l.size
}
type LogEntry struct {
startTime time.Time
client string
protocol string
method string
uri string
status int
duration time.Duration
size int
}
// NewLogEntry returns a log entry for request.
// startTime is the timestamp with which the entry is logged.
// status and size are the response HTTP status and size respectively.
func NewLogEntry(req *http.Request, url url.URL, startTime time.Time, status, size int) LogEntry {
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
uri := req.RequestURI
// Requests using the CONNECT method over HTTP/2.0 must use
// the authority field (aka r.Host) to identify the target.
// Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT
if req.ProtoMajor == 2 && req.Method == "CONNECT" {
uri = req.Host
}
if uri == "" {
uri = url.RequestURI()
}
return LogEntry{
startTime: startTime,
client: host,
protocol: req.Proto,
method: req.Method,
uri: uri,
status: status,
size: size,
duration: time.Since(startTime) / time.Millisecond,
}
}
func (entry LogEntry) Output() string {
return fmt.Sprintf(`{"time": %q, "client": %q, "protocol": %q, "method": %q, "uri": %q, "status": %d, "duration": %d, "size": %d}
`,
entry.startTime.Format("2006-01-02 15:04:05.999 Z07:00"),
entry.client, entry.protocol, entry.method, entry.uri, entry.status, entry.duration, entry.size)
}