caddy/middleware/log/log.go

58 lines
1.7 KiB
Go
Raw Normal View History

2015-03-29 06:50:42 +08:00
// Package log implements basic but useful request (access) logging middleware.
package log
2015-01-14 03:43:45 +08:00
import (
"fmt"
2015-01-14 03:43:45 +08:00
"log"
"net/http"
"github.com/mholt/caddy/middleware"
2015-01-14 03:43:45 +08:00
)
2015-05-25 10:52:34 +08:00
// Logger is a basic request logging middleware.
type Logger struct {
Next middleware.Handler
Rules []Rule
ErrorFunc func(http.ResponseWriter, *http.Request, int) // failover error handler
2015-03-29 06:50:42 +08:00
}
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)
if status >= 400 {
// There was an error up the chain, but no response has been written yet.
// The error must be handled here so the log entry will record the response size.
if l.ErrorFunc != nil {
l.ErrorFunc(responseRecorder, r, status)
} else {
// Default failover error handler
responseRecorder.WriteHeader(status)
fmt.Fprintf(responseRecorder, "%d %s", status, http.StatusText(status))
}
status = 0
}
2015-03-29 06:50:42 +08:00
rep := middleware.NewReplacer(r, responseRecorder)
rule.Log.Println(rep.Replace(rule.Format))
return status, err
2015-01-14 03:43:45 +08:00
}
}
return l.Next.ServeHTTP(w, r)
2015-03-29 06:50:42 +08:00
}
2015-01-14 03:43:45 +08:00
2015-05-25 10:52:34 +08:00
// Rule configures the logging middleware.
type Rule struct {
2015-03-29 06:50:42 +08:00
PathScope string
OutputFile string
Format string
Log *log.Logger
2015-01-14 03:43:45 +08:00
}
const (
DefaultLogFilename = "access.log"
CommonLogFormat = `{remote} ` + middleware.EmptyStringReplacer + ` [{when}] "{method} {uri} {proto}" {status} {size}`
CombinedLogFormat = CommonLogFormat + ` "{>Referer}" "{>User-Agent}"`
DefaultLogFormat = CommonLogFormat
2015-01-14 03:43:45 +08:00
)