traefik/middlewares/accesslog/logger_formatters.go

70 lines
1.6 KiB
Go
Raw Normal View History

2017-05-22 19:39:29 +00:00
package accesslog
import (
"bytes"
"fmt"
"time"
2018-01-22 11:16:03 +00:00
"github.com/sirupsen/logrus"
2017-05-22 19:39:29 +00:00
)
// default format for time presentation
2017-09-07 08:54:03 +00:00
const (
commonLogTimeFormat = "02/Jan/2006:15:04:05 -0700"
defaultValue = "-"
)
2017-05-22 19:39:29 +00:00
// CommonLogFormatter provides formatting in the Traefik common log format
type CommonLogFormatter struct{}
2017-05-22 19:39:29 +00:00
//Format formats the log entry in the Traefik common log format
func (f *CommonLogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b := &bytes.Buffer{}
timestamp := entry.Data[StartUTC].(time.Time).Format(commonLogTimeFormat)
elapsedMillis := entry.Data[Duration].(time.Duration).Nanoseconds() / 1000000
2017-09-07 08:54:03 +00:00
_, err := fmt.Fprintf(b, "%s - %s [%s] \"%s %s %s\" %v %v %s %s %v %s %s %dms\n",
2017-05-22 19:39:29 +00:00
entry.Data[ClientHost],
entry.Data[ClientUsername],
timestamp,
entry.Data[RequestMethod],
entry.Data[RequestPath],
entry.Data[RequestProtocol],
2018-01-11 09:04:03 +00:00
toLog(entry.Data[OriginStatus], defaultValue),
toLog(entry.Data[OriginContentSize], defaultValue),
toLog(entry.Data["request_Referer"], `"-"`),
toLog(entry.Data["request_User-Agent"], `"-"`),
toLog(entry.Data[RequestCount], defaultValue),
toLog(entry.Data[FrontendName], defaultValue),
toLog(entry.Data[BackendURL], defaultValue),
2017-05-22 19:39:29 +00:00
elapsedMillis)
return b.Bytes(), err
}
2018-01-11 09:04:03 +00:00
func toLog(v interface{}, defaultValue string) interface{} {
2017-05-22 19:39:29 +00:00
if v == nil {
return defaultValue
}
switch s := v.(type) {
case string:
return quoted(s, defaultValue)
case fmt.Stringer:
return quoted(s.String(), defaultValue)
default:
2017-09-07 08:54:03 +00:00
return v
2017-05-22 19:39:29 +00:00
}
}
func quoted(s string, defaultValue string) string {
if len(s) == 0 {
return defaultValue
}
return `"` + s + `"`
}