-
Notifications
You must be signed in to change notification settings - Fork 0
/
accesslog.go
86 lines (73 loc) · 2.24 KB
/
accesslog.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
package httpwaymid
import (
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
"github.com/corneldamian/httpway"
)
//this handler will write to logger function (the one form parameter) the w3c access log
//this are the fields:
//#Fields: c-ip x-c-user date time cs-method cs-uri-stem cs-uri-query cs(X-Forwarded-For) sc-bytes sc-status time-taken
//when you first init or change logging file, call AccessLogHeader to write the w3c fields
func AccessLog(logger func(v ...interface{})) httpway.Handler {
return func(w http.ResponseWriter, r *http.Request) {
ctx := httpway.GetContext(r)
starttime := time.Now()
ctx.Next(w, r)
username := "-"
if ctx.HasSession() && ctx.Session().Username() != "" {
username = ctx.Session().Username()
}
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
query := r.URL.RawQuery
if query == "" {
query = "-"
}
xforwarded := r.Header.Get("X-Forwarded-For")
if xforwarded != "" {
tmpsplit := strings.Split(xforwarded, ",")
if len(tmpsplit) > 0 {
xforwarded = tmpsplit[len(tmpsplit)-1]
}
xforwarded = strings.Trim(xforwarded, " ")
} else {
xforwarded = "-"
}
statuscode := ctx.StatusCode()
if statuscode == 0 {
statuscode = 200
}
logger("%s %s %s %s %s %s %s %d %d %d",
ip,
username,
starttime.UTC().Format("2006-01-02 15:04:05"),
r.Method,
r.URL.EscapedPath(),
query,
xforwarded,
ctx.TransferedBytes(),
statuscode,
time.Since(starttime).Nanoseconds()/1000,
)
}
}
//write w3c access log header
func AccessLogHeader(logger func(v ...interface{})) {
logger("#Version: 1.0")
logger("#Fields: c-ip x-c-user date time cs-method cs-uri-stem cs-uri-query cs(X-Forwarded-For) sc-bytes sc-status time-taken")
logger("#Software: httpway accesslog")
logger("#Start-Date: %s", time.Now().UTC().Format("2006-01-02 15:04:05"))
}
//write w3c access log header using io.Writer
func AccessLogHeaderWriter(w io.Writer) {
fmt.Fprint(w, "#Version: 1.0\n")
fmt.Fprint(w, "#Fields: c-ip x-c-user date time cs-method cs-uri-stem cs-uri-query cs(X-Forwarded-For) sc-bytes sc-status time-taken\n")
fmt.Fprint(w, "#Software: httpway accesslog\n")
fmt.Fprintf(w, "#Start-Date: %s\n", time.Now().UTC().Format("2006-01-02 15:04:05"))
}