mirror of
https://github.com/caddyserver/caddy.git
synced 2024-11-26 10:13:39 +08:00
6c1f2af53a
in the case of error (>=400) then no response may have been sent
50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
// Package log implements basic but useful request (access) logging middleware.
|
|
package log
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/mholt/caddy/middleware"
|
|
)
|
|
|
|
// Logger is a basic request logging middleware.
|
|
type Logger struct {
|
|
Next middleware.Handler
|
|
Rules []Rule
|
|
}
|
|
|
|
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 {
|
|
responseRecorder.WriteHeader(status)
|
|
fmt.Fprintf(responseRecorder, "%d %s", status, http.StatusText(status))
|
|
status = 0
|
|
}
|
|
rep := middleware.NewReplacer(r, responseRecorder)
|
|
rule.Log.Println(rep.Replace(rule.Format))
|
|
return status, err
|
|
}
|
|
}
|
|
return l.Next.ServeHTTP(w, r)
|
|
}
|
|
|
|
// Rule configures the logging middleware.
|
|
type Rule 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
|
|
)
|