-
Notifications
You must be signed in to change notification settings - Fork 0
/
apachelog.go
54 lines (45 loc) · 1.27 KB
/
apachelog.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
package main
import (
"fmt"
"log"
"strings"
"time"
"gopkg.in/macaron.v1"
)
const (
apacheFormatPattern = "%s - - [%s] \"%s %d %d\" %f\n"
apacheLogTimeFormat = "02/Jan/2006 03:04:05"
)
type apacheLogRecord struct {
ip string
time time.Time
method, uri, protocol string
status int
responseBytes int64
elapsedTime time.Duration
}
func apacheLogHandler() macaron.Handler {
return func(ctx *macaron.Context) {
clientIP := ctx.Req.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
rw := ctx.Resp.(macaron.ResponseWriter)
startTime := time.Now()
ctx.Next()
finishTime := time.Now()
r := &apacheLogRecord{
ip: ctx.Req.RemoteAddr,
time: finishTime.UTC(),
method: ctx.Req.Method,
uri: ctx.Req.RequestURI,
protocol: ctx.Req.Proto,
status: rw.Status(),
elapsedTime: finishTime.Sub(startTime),
responseBytes: int64(rw.Size()),
}
timeFormatted := r.time.Format(apacheLogTimeFormat)
requestLine := fmt.Sprintf("%s %s %s", r.method, r.uri, r.protocol)
log.Printf(apacheFormatPattern, r.ip, timeFormatted, requestLine, r.status, r.responseBytes, r.elapsedTime.Seconds())
}
}