0
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-23 22:27:38 -05:00
caddy/middleware/log/log.go

72 lines
1.6 KiB
Go
Raw Normal View History

// Package log implements basic but useful request logging middleware.
package log
2015-01-13 14:43:45 -05:00
import (
"log"
"net/http"
"os"
"github.com/mholt/caddy/middleware"
2015-01-13 14:43:45 -05:00
)
// New instantiates a new instance of logging middleware.
func New(c middleware.Controller) (middleware.Middleware, error) {
var logWhat, outputFile, format string
var logger *log.Logger
for c.Next() {
c.Args(&logWhat, &outputFile, &format)
if logWhat == "" {
return nil, c.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
}
}
// Open the log file for writing when the server starts
c.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, 0644)
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 := middleware.NewResponseRecorder(w)
2015-01-13 14:43:45 -05:00
next(sw, r)
rep := middleware.NewReplacer(r, sw)
logger.Println(rep.Replace(format))
2015-01-13 14:43:45 -05:00
}
}, nil
2015-01-13 14:43:45 -05:00
}
const (
defaultLogFilename = "access.log"
commonLogFormat = `{remote} ` + middleware.EmptyStringReplacer + ` [{when}] "{method} {uri} {proto}" {status} {size}`
2015-01-13 14:43:45 -05:00
combinedLogFormat = commonLogFormat + ` "{>Referer}" "{>User-Agent}"`
defaultReqLogFormat = commonLogFormat
)