traefik/middlewares/accesslog/logger_formatters.go

84 lines
2.1 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
)
2018-11-14 09:18:03 +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
2018-11-14 09:18:03 +00:00
// CommonLogFormatter provides formatting in the Traefik common log format.
type CommonLogFormatter struct{}
2017-05-22 19:39:29 +00:00
2018-11-14 09:18:03 +00:00
// Format formats the log entry in the Traefik common log format.
2017-05-22 19:39:29 +00:00
func (f *CommonLogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
b := &bytes.Buffer{}
2018-03-14 13:12:04 +00:00
var timestamp = defaultValue
if v, ok := entry.Data[StartUTC]; ok {
timestamp = v.(time.Time).Format(commonLogTimeFormat)
}
var elapsedMillis int64
if v, ok := entry.Data[Duration]; ok {
elapsedMillis = v.(time.Duration).Nanoseconds() / 1000000
}
2017-05-22 19:39:29 +00:00
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",
2018-03-14 13:12:04 +00:00
toLog(entry.Data, ClientHost, defaultValue, false),
toLog(entry.Data, ClientUsername, defaultValue, false),
2017-05-22 19:39:29 +00:00
timestamp,
2018-03-14 13:12:04 +00:00
toLog(entry.Data, RequestMethod, defaultValue, false),
toLog(entry.Data, RequestPath, defaultValue, false),
toLog(entry.Data, RequestProtocol, defaultValue, false),
toLog(entry.Data, OriginStatus, defaultValue, true),
toLog(entry.Data, OriginContentSize, defaultValue, true),
toLog(entry.Data, "request_Referer", `"-"`, true),
toLog(entry.Data, "request_User-Agent", `"-"`, true),
toLog(entry.Data, RequestCount, defaultValue, true),
2018-11-14 09:18:03 +00:00
toLog(entry.Data, RouterName, defaultValue, true),
toLog(entry.Data, ServiceURL, defaultValue, true),
2017-05-22 19:39:29 +00:00
elapsedMillis)
return b.Bytes(), err
}
2018-03-14 13:12:04 +00:00
func toLog(fields logrus.Fields, key string, defaultValue string, quoted bool) interface{} {
if v, ok := fields[key]; ok {
if v == nil {
return defaultValue
}
2017-05-22 19:39:29 +00:00
2018-03-14 13:12:04 +00:00
switch s := v.(type) {
case string:
return toLogEntry(s, defaultValue, quoted)
2017-05-22 19:39:29 +00:00
2018-03-14 13:12:04 +00:00
case fmt.Stringer:
return toLogEntry(s.String(), defaultValue, quoted)
2017-05-22 19:39:29 +00:00
2018-03-14 13:12:04 +00:00
default:
return v
}
2017-05-22 19:39:29 +00:00
}
2018-03-14 13:12:04 +00:00
return defaultValue
2017-05-22 19:39:29 +00:00
}
2018-11-14 09:18:03 +00:00
2018-03-14 13:12:04 +00:00
func toLogEntry(s string, defaultValue string, quote bool) string {
2017-05-22 19:39:29 +00:00
if len(s) == 0 {
return defaultValue
}
2018-03-14 13:12:04 +00:00
if quote {
return `"` + s + `"`
}
return s
2017-05-22 19:39:29 +00:00
}