2015-01-13 14:43:45 -05:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2015-01-19 01:11:21 -05:00
|
|
|
"os"
|
2015-01-13 14:43:45 -05:00
|
|
|
)
|
|
|
|
|
2015-01-19 01:11:21 -05:00
|
|
|
func RequestLog(p parser) Middleware {
|
|
|
|
var logWhat, outputFile, format string
|
|
|
|
var logger *log.Logger
|
|
|
|
|
|
|
|
for p.Next() {
|
|
|
|
p.Args(&logWhat, &outputFile, &format)
|
|
|
|
|
|
|
|
if logWhat == "" {
|
|
|
|
return p.ArgErr()
|
|
|
|
}
|
|
|
|
if outputFile == "" {
|
|
|
|
outputFile = defaultLogFilename
|
|
|
|
}
|
|
|
|
switch format {
|
|
|
|
case "":
|
|
|
|
format = defaultReqLogFormat
|
|
|
|
case "{common}":
|
|
|
|
format = commonLogFormat
|
|
|
|
case "{combined}":
|
|
|
|
format = combinedLogFormat
|
2015-01-13 14:43:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-01-19 01:11:21 -05:00
|
|
|
// Open the log file for writing when the server starts
|
|
|
|
p.Startup(func() error {
|
|
|
|
var err error
|
|
|
|
var file *os.File
|
|
|
|
|
|
|
|
if outputFile == "stdout" {
|
|
|
|
file = os.Stdout
|
|
|
|
} else if outputFile == "stderr" {
|
|
|
|
file = os.Stderr
|
|
|
|
} else {
|
|
|
|
file, err = os.OpenFile(outputFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
logger = log.New(file, "", 0)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
2015-01-13 14:43:45 -05:00
|
|
|
return func(next http.HandlerFunc) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
sw := newResponseRecorder(w)
|
|
|
|
next(sw, r)
|
2015-01-19 01:11:21 -05:00
|
|
|
rep := newReplacer(r, sw)
|
|
|
|
logger.Println(rep.replace(format))
|
2015-01-13 14:43:45 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2015-01-19 01:11:21 -05:00
|
|
|
defaultLogFilename = "access.log"
|
2015-01-19 19:12:38 -05:00
|
|
|
commonLogFormat = `{remote} ` + emptyStringReplacer + ` [{when}] "{method} {uri} {proto}" {status} {size}`
|
2015-01-13 14:43:45 -05:00
|
|
|
combinedLogFormat = commonLogFormat + ` "{>Referer}" "{>User-Agent}"`
|
|
|
|
defaultReqLogFormat = commonLogFormat
|
|
|
|
)
|