summaryrefslogtreecommitdiffhomepage
path: root/middleware/log/log.go
blob: 39d8ae038321ff064455c04cd94896fb1ebdda09 (plain)
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
// Package log implements basic but useful request (access) logging middleware.
package log

import (
	"log"
	"net/http"

	"github.com/mholt/caddy/middleware"
)

type Logger struct {
	Next  middleware.Handler
	Rules []LogRule
}

func (l Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	for _, rule := range l.Rules {
		if middleware.Path(r.URL.Path).Matches(rule.PathScope) {
			responseRecorder := middleware.NewResponseRecorder(w)
			status, err := l.Next.ServeHTTP(responseRecorder, r)
			rep := middleware.NewReplacer(r, responseRecorder)
			rule.Log.Println(rep.Replace(rule.Format))
			return status, err
		}
	}
	return l.Next.ServeHTTP(w, r)
}

type LogRule struct {
	PathScope  string
	OutputFile string
	Format     string
	Log        *log.Logger
}

const (
	DefaultLogFilename = "access.log"
	CommonLogFormat    = `{remote} ` + middleware.EmptyStringReplacer + ` [{when}] "{method} {uri} {proto}" {status} {size}`
	CombinedLogFormat  = CommonLogFormat + ` "{>Referer}" "{>User-Agent}"`
	DefaultLogFormat   = CommonLogFormat
)