2015-03-28 17:50:42 -05:00
|
|
|
// Package log implements basic but useful request (access) logging middleware.
|
2015-01-30 00:05:21 -05:00
|
|
|
package log
|
2015-01-13 14:43:45 -05:00
|
|
|
|
|
|
|
import (
|
2015-06-12 11:21:19 -05:00
|
|
|
"fmt"
|
2015-01-13 14:43:45 -05:00
|
|
|
"log"
|
|
|
|
"net/http"
|
2015-01-30 00:05:21 -05:00
|
|
|
|
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-01-13 14:43:45 -05:00
|
|
|
)
|
|
|
|
|
2015-05-24 21:52:34 -05:00
|
|
|
// Logger is a basic request logging middleware.
|
2015-05-04 07:53:54 -05:00
|
|
|
type Logger struct {
|
|
|
|
Next middleware.Handler
|
2015-05-24 21:52:34 -05:00
|
|
|
Rules []Rule
|
2015-03-28 17:50:42 -05: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)
|
2015-04-03 00:30:54 -05:00
|
|
|
status, err := l.Next.ServeHTTP(responseRecorder, r)
|
2015-06-12 11:21:19 -05:00
|
|
|
if status >= 400 {
|
|
|
|
responseRecorder.WriteHeader(status)
|
|
|
|
fmt.Fprintf(responseRecorder, "%d %s", status, http.StatusText(status))
|
|
|
|
status = 0
|
|
|
|
}
|
2015-03-28 17:50:42 -05:00
|
|
|
rep := middleware.NewReplacer(r, responseRecorder)
|
|
|
|
rule.Log.Println(rep.Replace(rule.Format))
|
|
|
|
return status, err
|
2015-01-13 14:43:45 -05:00
|
|
|
}
|
|
|
|
}
|
2015-04-03 00:30:54 -05:00
|
|
|
return l.Next.ServeHTTP(w, r)
|
2015-03-28 17:50:42 -05:00
|
|
|
}
|
2015-01-13 14:43:45 -05:00
|
|
|
|
2015-05-24 21:52:34 -05:00
|
|
|
// Rule configures the logging middleware.
|
|
|
|
type Rule struct {
|
2015-03-28 17:50:42 -05:00
|
|
|
PathScope string
|
|
|
|
OutputFile string
|
|
|
|
Format string
|
|
|
|
Log *log.Logger
|
2015-01-13 14:43:45 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2015-05-04 07:53:54 -05:00
|
|
|
DefaultLogFilename = "access.log"
|
|
|
|
CommonLogFormat = `{remote} ` + middleware.EmptyStringReplacer + ` [{when}] "{method} {uri} {proto}" {status} {size}`
|
|
|
|
CombinedLogFormat = CommonLogFormat + ` "{>Referer}" "{>User-Agent}"`
|
|
|
|
DefaultLogFormat = CommonLogFormat
|
2015-01-13 14:43:45 -05:00
|
|
|
)
|