forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.go
68 lines (54 loc) · 1.52 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
// Copyright 2017 Gerasimos Maropoulos, ΓΜ. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package logger provides request logging via middleware. See _examples/beginner/request-logger
package logger
import (
"strconv"
"time"
"github.com/kataras/iris/context"
)
type requestLoggerMiddleware struct {
config Config
}
// Serve serves the middleware
func (l *requestLoggerMiddleware) ServeHTTP(ctx context.Context) {
//all except latency to string
var status, ip, method, path string
var latency time.Duration
var startTime, endTime time.Time
path = ctx.Path()
method = ctx.Method()
startTime = time.Now()
ctx.Next()
//no time.Since in order to format it well after
endTime = time.Now()
latency = endTime.Sub(startTime)
if l.config.Status {
status = strconv.Itoa(ctx.GetStatusCode())
}
if l.config.IP {
ip = ctx.RemoteAddr()
}
if !l.config.Method {
method = ""
}
if !l.config.Path {
path = ""
}
//finally print the logs, no new line, the framework's logger is responsible how to render each log.
ctx.Application().Log("%v %4v %s %s %s", status, latency, ip, method, path)
}
// New creates and returns a new request logger middleware.
// Do not confuse it with the framework's Logger.
// This is for the http requests.
//
// Receives an optional configuation.
func New(cfg ...Config) context.Handler {
c := DefaultConfiguration()
if len(cfg) > 0 {
c = cfg[0]
}
l := &requestLoggerMiddleware{config: c}
return l.ServeHTTP
}