Skip to content

Commit ebe6d68

Browse files
committed
Initial commit
0 parents  commit ebe6d68

File tree

5 files changed

+211
-0
lines changed

5 files changed

+211
-0
lines changed

LICENSE

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Copyright 2020 Aaron Van Bokhoven
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4+
5+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6+
7+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# aaronvb/logrequest
2+
Package `aaronvb/logrequest` is a Go middleware log output inspired by the Ruby on Rails log out for requests. Example output:
3+
4+
```sh
5+
Started GET "/" 127.0.0.1:12345 HTTP/1.1
6+
Completed 200 in 3.7455ms
7+
```
8+
9+
The output can directly sent to `log.Logger` or to a map[string]string with the key `started` and `completed`.
10+
11+
## Install
12+
```sh
13+
go get -u github.com/aaronvb/logrequest
14+
```

go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/aaronvb/logrequest
2+
3+
go 1.14

logrequest.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package logrequest
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"time"
8+
)
9+
10+
// LogRequest struct
11+
// Pass values from middleware to this struct
12+
type LogRequest struct {
13+
Writer http.ResponseWriter
14+
Request *http.Request
15+
Handler http.Handler
16+
}
17+
18+
type statusWriter struct {
19+
http.ResponseWriter
20+
statusCode int
21+
}
22+
23+
// ToLogger will print the Started and Completed request info to the passed logger
24+
func (lr LogRequest) ToLogger(logger *log.Logger) {
25+
sw, completedDuration := lr.parseRequest()
26+
logger.Printf(`Started %s "%s" %s %s`, lr.Request.Method, lr.Request.URL.RequestURI(), lr.Request.RemoteAddr, lr.Request.Proto)
27+
logger.Printf("Completed %d in %s", sw.statusCode, completedDuration)
28+
}
29+
30+
// ToString will return a map with the key 'started' and 'completed' that contain
31+
// a string output for eacch
32+
func (lr LogRequest) ToString() map[string]string {
33+
sw, completedDuration := lr.parseRequest()
34+
ts := make(map[string]string)
35+
ts["started"] = fmt.Sprintf(`Started %s "%s" %s %s`, lr.Request.Method, lr.Request.URL.RequestURI(), lr.Request.RemoteAddr, lr.Request.Proto)
36+
ts["completed"] = fmt.Sprintf("Completed %d in %s", sw.statusCode, completedDuration)
37+
38+
return ts
39+
}
40+
41+
// parseRequest will time the request and retrieve the status from the
42+
// ResponseWriter. Returns the statusWriter struct and the duration
43+
// of the request.
44+
func (lr LogRequest) parseRequest() (statusWriter, time.Duration) {
45+
startTime := time.Now()
46+
sw := statusWriter{ResponseWriter: lr.Writer}
47+
lr.Handler.ServeHTTP(&sw, lr.Request)
48+
return sw, time.Now().Sub(startTime)
49+
}
50+
51+
func (w *statusWriter) WriteHeader(statusCode int) {
52+
w.statusCode = statusCode
53+
w.ResponseWriter.WriteHeader(statusCode)
54+
}
55+
56+
func (w *statusWriter) Write(b []byte) (int, error) {
57+
if w.statusCode == 0 {
58+
w.statusCode = 200
59+
}
60+
61+
n, err := w.ResponseWriter.Write(b)
62+
return n, err
63+
}

logrequest_test.go

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
package logrequest
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"log"
7+
"net/http"
8+
"net/http/httptest"
9+
"strings"
10+
"testing"
11+
)
12+
13+
func TestToLogger(t *testing.T) {
14+
tables := []struct {
15+
statusCode int
16+
method string
17+
path string
18+
expectedStartedResults string
19+
expectedCompletedResults string
20+
}{
21+
{http.StatusOK, http.MethodGet, "/foo", fmt.Sprintf(`Started %s "%s"`, http.MethodGet, "/foo"), fmt.Sprintf("Completed %d in", http.StatusOK)},
22+
{http.StatusUnauthorized, http.MethodPost, "/bar/create", fmt.Sprintf(`Started %s "%s"`, http.MethodPost, "/bar/create"), fmt.Sprintf("Completed %d in", http.StatusUnauthorized)},
23+
{http.StatusNotFound, http.MethodGet, "/hello/world", fmt.Sprintf(`Started %s "%s"`, http.MethodGet, "/hello/world"), fmt.Sprintf("Completed %d in", http.StatusNotFound)},
24+
{http.StatusInternalServerError, http.MethodGet, "/", fmt.Sprintf(`Started %s "%s"`, http.MethodGet, "/"), fmt.Sprintf("Completed %d in", http.StatusInternalServerError)},
25+
{http.StatusServiceUnavailable, http.MethodPut, "/foo/update", fmt.Sprintf(`Started %s "%s"`, http.MethodPut, "/foo/update"), fmt.Sprintf("Completed %d in", http.StatusServiceUnavailable)},
26+
}
27+
28+
for _, table := range tables {
29+
var str bytes.Buffer
30+
var logger = log.Logger{}
31+
logger.SetOutput(&str)
32+
33+
app := &application{
34+
infoLog: &logger,
35+
}
36+
req, err := http.NewRequest(table.method, table.path, nil)
37+
if err != nil {
38+
t.Fatal(err)
39+
}
40+
41+
testHandler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
42+
rw.WriteHeader(table.statusCode)
43+
})
44+
45+
rr := httptest.NewRecorder()
46+
handler := app.logRequestToLogger(testHandler)
47+
handler.ServeHTTP(rr, req)
48+
49+
if strings.Contains(str.String(), table.expectedStartedResults) == false {
50+
t.Errorf("Expected output was incorrect, %s does not contain %s", str.String(), table.expectedStartedResults)
51+
}
52+
53+
if strings.Contains(str.String(), table.expectedCompletedResults) == false {
54+
t.Errorf("Expected output was incorrect, %s does not contain %s", str.String(), table.expectedCompletedResults)
55+
}
56+
}
57+
}
58+
59+
func TestToString(t *testing.T) {
60+
tables := []struct {
61+
statusCode int
62+
method string
63+
path string
64+
expectedStartedResults string
65+
expectedCompletedResults string
66+
}{
67+
{http.StatusOK, http.MethodGet, "/foo", fmt.Sprintf(`Started %s "%s"`, http.MethodGet, "/foo"), fmt.Sprintf("Completed %d in", http.StatusOK)},
68+
{http.StatusUnauthorized, http.MethodPost, "/bar/create", fmt.Sprintf(`Started %s "%s"`, http.MethodPost, "/bar/create"), fmt.Sprintf("Completed %d in", http.StatusUnauthorized)},
69+
{http.StatusNotFound, http.MethodGet, "/hello/world", fmt.Sprintf(`Started %s "%s"`, http.MethodGet, "/hello/world"), fmt.Sprintf("Completed %d in", http.StatusNotFound)},
70+
{http.StatusInternalServerError, http.MethodGet, "/", fmt.Sprintf(`Started %s "%s"`, http.MethodGet, "/"), fmt.Sprintf("Completed %d in", http.StatusInternalServerError)},
71+
{http.StatusServiceUnavailable, http.MethodPut, "/foo/update", fmt.Sprintf(`Started %s "%s"`, http.MethodPut, "/foo/update"), fmt.Sprintf("Completed %d in", http.StatusServiceUnavailable)},
72+
}
73+
74+
for _, table := range tables {
75+
var str bytes.Buffer
76+
var logger = log.Logger{}
77+
logger.SetOutput(&str)
78+
79+
app := &application{
80+
infoLog: &logger,
81+
}
82+
req, err := http.NewRequest(table.method, table.path, nil)
83+
if err != nil {
84+
t.Fatal(err)
85+
}
86+
87+
testHandler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
88+
rw.WriteHeader(table.statusCode)
89+
})
90+
91+
rr := httptest.NewRecorder()
92+
handler := app.logRequestToString(testHandler)
93+
handler.ServeHTTP(rr, req)
94+
95+
if strings.Contains(str.String(), table.expectedStartedResults) == false {
96+
t.Errorf("Expected output was incorrect, %s does not contain %s", str.String(), table.expectedStartedResults)
97+
}
98+
99+
if strings.Contains(str.String(), table.expectedCompletedResults) == false {
100+
t.Errorf("Expected output was incorrect, %s does not contain %s", str.String(), table.expectedCompletedResults)
101+
}
102+
}
103+
}
104+
105+
// Helpers
106+
107+
type application struct {
108+
infoLog *log.Logger
109+
}
110+
111+
func (app *application) logRequestToLogger(next http.Handler) http.Handler {
112+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113+
lr := LogRequest{Request: r, Writer: w, Handler: next}
114+
lr.ToLogger(app.infoLog)
115+
})
116+
}
117+
118+
func (app *application) logRequestToString(next http.Handler) http.Handler {
119+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
120+
lr := LogRequest{Request: r, Writer: w, Handler: next}
121+
app.infoLog.Println(lr.ToString()["started"])
122+
app.infoLog.Println(lr.ToString()["completed"])
123+
})
124+
}

0 commit comments

Comments
 (0)