Skip to content

Commit 9a363d6

Browse files
authored
Merge pull request #1 from gcp-kit/feat/context-logger-key-to-public
Feat context logger key to public / minor fix and update
2 parents a434c26 + 592c1ce commit 9a363d6

File tree

11 files changed

+278
-66
lines changed

11 files changed

+278
-66
lines changed

.github/.golangci.yml

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
linters-settings:
2+
dupl:
3+
threshold: 100
4+
goconst:
5+
min-len: 2
6+
min-occurrences: 2
7+
goimports:
8+
local-prefixes: github.com/golangci/golangci-lint
9+
revive:
10+
ignore-generated-header: false
11+
confidence: 0.3
12+
govet:
13+
check-shadowing: true
14+
lll:
15+
line-length: 120
16+
misspell:
17+
locale: US
18+
ignore-words: []
19+
20+
linters:
21+
disable-all: true
22+
enable:
23+
- bodyclose
24+
- deadcode
25+
- dogsled
26+
- dupl
27+
- errcheck
28+
- goconst
29+
- gofmt
30+
- goimports
31+
- revive
32+
- govet
33+
- ineffassign
34+
- misspell
35+
- exportloopref
36+
- staticcheck
37+
- structcheck
38+
- unconvert
39+
- unused
40+
- varcheck
41+
- whitespace
42+
43+
issues:
44+
exclude:
45+
- declaration of "(err|ctx)" shadows declaration at
46+
- echo
47+
exclude-rules:
48+
- path: _test\.go
49+
linters:
50+
- dupl
51+
- gomnd
52+
53+
service:
54+
golangci-lint-version: 1.41.x
55+
prepare:
56+
- echo "here I can run custom commands, but no preparation needed for this repo"

.github/PULL_REQUEST_TEMPLATE.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<!-- This is a template. Please rewrite to the necessary contents when creating the PR. -->
2+
<!-- If there is an issue, enter it. -->
3+
- Closes #XXX
4+
5+
<!-- ## Overview -->
6+
<!-- Please write the purpose of this PR and the outline of implementation. -->

.github/workflows/build.yml

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
name: build
2+
3+
on:
4+
pull_request:
5+
push:
6+
branches:
7+
- master
8+
9+
jobs:
10+
go:
11+
name: runner / go
12+
13+
runs-on: ubuntu-latest
14+
15+
steps:
16+
- name: Check out code into the Go module directory
17+
uses: actions/checkout@v2
18+
19+
- uses: actions/setup-go@v2
20+
with:
21+
go-version: '^1.13'
22+
23+
- uses: actions/cache@v2
24+
with:
25+
path: ~/go/pkg/mod
26+
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
27+
restore-keys: |
28+
${{ runner.os }}-go-
29+
30+
- name: build
31+
run: go get .

.github/workflows/linter.yml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
name: linter
2+
3+
on:
4+
pull_request:
5+
push:
6+
branches:
7+
- master
8+
9+
jobs:
10+
golangci-lint:
11+
name: runner / golangci-lint
12+
13+
runs-on: ubuntu-latest
14+
15+
steps:
16+
- name: Check out code into the Go module directory
17+
uses: actions/checkout@v2
18+
19+
- uses: actions/setup-go@v2
20+
with:
21+
go-version: '^1.13'
22+
23+
- name: golangci-lint
24+
uses: golangci/golangci-lint-action@v2
25+
with:
26+
args: "--config=.github/.golangci.yml --timeout=10m"
27+
skip-go-installation: true
28+
skip-pkg-cache: true
29+
skip-build-cache: true

.github/workflows/test.yml

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
name: test
2+
3+
on:
4+
pull_request:
5+
push:
6+
branches:
7+
- master
8+
9+
jobs:
10+
go:
11+
name: runner / go
12+
13+
runs-on: ubuntu-latest
14+
15+
steps:
16+
- name: Set up Go ^1.13
17+
uses: actions/setup-go@v2
18+
with:
19+
go-version: '^1.13'
20+
id: go
21+
22+
- uses: actions/checkout@v2
23+
24+
- uses: actions/cache@v2
25+
with:
26+
path: ~/go/pkg/mod
27+
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
28+
restore-keys: |
29+
${{ runner.os }}-go-
30+
31+
- name: Run tests
32+
run: go test -v ./...

context.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,4 @@ package stalog
22

33
type contextKey struct{}
44

5-
var (
6-
contextLoggerKey = &contextKey{}
7-
)
5+
var ContextLoggerKey = &contextKey{}

go.mod

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
module github.com/gcp-kit/stalog
22

3-
go 1.12
3+
go 1.13
44

55
require (
66
github.com/go-chi/chi v4.0.3+incompatible
7-
github.com/google/go-cmp v0.3.0
8-
github.com/labstack/echo/v4 v4.1.16
9-
go.opencensus.io v0.22.3
7+
github.com/google/go-cmp v0.5.3
8+
github.com/labstack/echo/v4 v4.5.0
9+
go.opencensus.io v0.23.0
1010
)

go.sum

Lines changed: 74 additions & 24 deletions
Large diffs are not rendered by default.

middleware.go

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,17 @@ func RequestLogging(config *Config) func(http.Handler) http.Handler {
2727
reserve.LastHandling(wrw)
2828
}()
2929

30-
next.ServeHTTP(wrw, r)
30+
next.ServeHTTP(wrw, reserve.request)
3131
}
32+
3233
return http.HandlerFunc(fn)
3334
}
3435
}
3536

3637
// RequestLoggingWithEcho creates the middleware which logs a request log and creates a request-context logger
3738
func RequestLoggingWithEcho(config *Config) echo.MiddlewareFunc {
3839
return func(next echo.HandlerFunc) echo.HandlerFunc {
39-
fn := func(c echo.Context) error {
40+
return func(c echo.Context) error {
4041
reserve := NewReserve(config, c.Request())
4142

4243
wrw := &wrappedResponseWriter{
@@ -53,7 +54,6 @@ func RequestLoggingWithEcho(config *Config) echo.MiddlewareFunc {
5354

5455
return next(c)
5556
}
56-
return fn
5757
}
5858
}
5959

@@ -99,7 +99,7 @@ func NewReserve(config *Config, r *http.Request) *Reserve {
9999
loggedSeverity: make([]Severity, 0, 10),
100100
Skip: config.Skip,
101101
}
102-
ctx := context.WithValue(r.Context(), contextLoggerKey, contextLogger)
102+
ctx := context.WithValue(r.Context(), ContextLoggerKey, contextLogger)
103103

104104
return &Reserve{
105105
before: before,
@@ -159,15 +159,15 @@ func (w *wrappedResponseWriter) Write(b []byte) (int, error) {
159159
return n, err
160160
}
161161

162-
type HttpRequest struct {
162+
type HTTPRequest struct {
163163
RequestMethod string `json:"requestMethod"`
164164
RequestUrl string `json:"requestUrl"`
165165
RequestSize string `json:"requestSize"`
166166
Status int `json:"status"`
167167
ResponseSize string `json:"responseSize"`
168168
UserAgent string `json:"userAgent"`
169-
RemoteIp string `json:"remoteIp"`
170-
ServerIp string `json:"serverIp"`
169+
RemoteIP string `json:"remoteIp"`
170+
ServerIP string `json:"serverIp"`
171171
Referer string `json:"referer"`
172172
Latency string `json:"latency"`
173173
CacheLookup bool `json:"cacheLookup"`
@@ -176,28 +176,28 @@ type HttpRequest struct {
176176
Protocol string `json:"protocol"`
177177
}
178178

179-
type HttpRequestLog struct {
179+
type HTTPRequestLog struct {
180180
Time string `json:"time"`
181181
Trace string `json:"logging.googleapis.com/trace"`
182182
Severity string `json:"severity"`
183-
HttpRequest HttpRequest `json:"httpRequest"`
183+
HTTPRequest HTTPRequest `json:"httpRequest"`
184184
AdditionalData AdditionalData `json:"data,omitempty"`
185185
}
186186

187187
func writeRequestLog(r *http.Request, config *Config, status int, responseSize int, elapsed time.Duration, trace string, severity Severity) error {
188-
requestLog := &HttpRequestLog{
188+
requestLog := &HTTPRequestLog{
189189
Time: time.Now().Format(time.RFC3339Nano),
190190
Trace: trace,
191191
Severity: severity.String(),
192-
HttpRequest: HttpRequest{
192+
HTTPRequest: HTTPRequest{
193193
RequestMethod: r.Method,
194194
RequestUrl: r.URL.RequestURI(),
195195
RequestSize: fmt.Sprintf("%d", r.ContentLength),
196196
Status: status,
197197
ResponseSize: fmt.Sprintf("%d", responseSize),
198198
UserAgent: r.UserAgent(),
199-
RemoteIp: getRemoteIp(r),
200-
ServerIp: getServerIp(),
199+
RemoteIP: getRemoteIP(r),
200+
ServerIP: getServerIP(),
201201
Referer: r.Referer(),
202202
Latency: fmt.Sprintf("%fs", elapsed.Seconds()),
203203
CacheLookup: false,
@@ -207,31 +207,36 @@ func writeRequestLog(r *http.Request, config *Config, status int, responseSize i
207207
},
208208
AdditionalData: config.AdditionalData,
209209
}
210-
requestLogJson, err := json.Marshal(requestLog)
210+
211+
jsonByte, err := json.Marshal(requestLog)
211212
if err != nil {
212213
return err
213214
}
214-
requestLogJson = append(requestLogJson, '\n')
215215

216-
_, err = config.RequestLogOut.Write(requestLogJson)
216+
// append \n
217+
jsonByte = append(jsonByte, 0xa)
218+
219+
_, err = config.RequestLogOut.Write(jsonByte)
217220
return err
218221
}
219222

220-
func getRemoteIp(r *http.Request) string {
223+
func getRemoteIP(r *http.Request) string {
221224
parts := strings.Split(r.RemoteAddr, ":")
222225
return parts[0]
223226
}
224227

225-
func getServerIp() string {
228+
func getServerIP() string {
226229
ifaces, err := net.Interfaces()
227230
if err != nil {
228231
return ""
229232
}
233+
230234
for _, i := range ifaces {
231235
addrs, err := i.Addrs()
232236
if err != nil {
233237
return ""
234238
}
239+
235240
for _, addr := range addrs {
236241
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
237242
if ipnet.IP.To4() != nil {
@@ -240,5 +245,6 @@ func getServerIp() string {
240245
}
241246
}
242247
}
248+
243249
return ""
244250
}

stackdriver.go

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,9 @@ func (s Severity) String() string {
8080
return "ALERT"
8181
case SeverityEmergency:
8282
return "EMERGENCY"
83+
default:
84+
return "UNKNOWN"
8385
}
84-
return "UNKNOWN"
8586
}
8687

8788
type SourceLocation struct {
@@ -112,7 +113,7 @@ type ContextLogger struct {
112113
// RequestContextLogger gets request-context logger for the request.
113114
// You must use `RequestLogging` middleware in advance for this function to work.
114115
func RequestContextLogger(r *http.Request) *ContextLogger {
115-
v, _ := r.Context().Value(contextLoggerKey).(*ContextLogger)
116+
v, _ := r.Context().Value(ContextLoggerKey).(*ContextLogger)
116117
return v
117118
}
118119

@@ -293,14 +294,16 @@ func (l *ContextLogger) write(severity Severity, msg string) error {
293294
AdditionalData: l.AdditionalData,
294295
}
295296

296-
logJson, err := json.Marshal(log)
297+
jsonByte, err := json.Marshal(log)
297298
if err != nil {
298299
_, _ = fmt.Fprintln(os.Stderr, err.Error())
299300
return err
300301
}
301-
logJson = append(logJson, '\n')
302302

303-
_, err = l.out.Write(logJson)
303+
// append \n
304+
jsonByte = append(jsonByte, 0xa)
305+
306+
_, err = l.out.Write(jsonByte)
304307
return err
305308
}
306309

@@ -311,5 +314,6 @@ func (l *ContextLogger) maxSeverity() Severity {
311314
max = s
312315
}
313316
}
317+
314318
return max
315319
}

0 commit comments

Comments
 (0)