2014-03-11 03:22:08 +04:00
|
|
|
package logrus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2016-11-17 22:28:41 +03:00
|
|
|
type fieldKey string
|
|
|
|
|
|
|
|
const (
|
|
|
|
DefaultKeyMsg = "msg"
|
|
|
|
DefaultKeyLevel = "level"
|
|
|
|
DefaultKeyTime = "time"
|
|
|
|
)
|
|
|
|
|
2015-04-04 03:25:25 +03:00
|
|
|
type JSONFormatter struct {
|
|
|
|
// TimestampFormat sets the format used for marshaling timestamps.
|
|
|
|
TimestampFormat string
|
2016-08-15 21:04:25 +03:00
|
|
|
MessageKey string
|
|
|
|
LevelKey string
|
|
|
|
TimeKey string
|
2015-04-04 03:25:25 +03:00
|
|
|
}
|
2014-03-11 03:22:08 +04:00
|
|
|
|
|
|
|
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
2014-12-10 05:53:40 +03:00
|
|
|
data := make(Fields, len(entry.Data)+3)
|
|
|
|
for k, v := range entry.Data {
|
2015-03-10 19:04:57 +03:00
|
|
|
switch v := v.(type) {
|
|
|
|
case error:
|
|
|
|
// Otherwise errors are ignored by `encoding/json`
|
|
|
|
// https://github.com/Sirupsen/logrus/issues/137
|
|
|
|
data[k] = v.Error()
|
|
|
|
default:
|
2015-03-09 18:15:08 +03:00
|
|
|
data[k] = v
|
|
|
|
}
|
2014-12-10 05:53:40 +03:00
|
|
|
}
|
|
|
|
prefixFieldClashes(data)
|
2015-04-04 03:25:25 +03:00
|
|
|
|
2015-05-26 16:02:13 +03:00
|
|
|
timestampFormat := f.TimestampFormat
|
|
|
|
if timestampFormat == "" {
|
|
|
|
timestampFormat = DefaultTimestampFormat
|
2015-04-04 03:25:25 +03:00
|
|
|
}
|
|
|
|
|
2016-11-17 22:28:41 +03:00
|
|
|
data[f.resolveKey(f.TimeKey, DefaultKeyTime)] = entry.Time.Format(timestampFormat)
|
|
|
|
data[f.resolveKey(f.MessageKey, DefaultKeyMsg)] = entry.Message
|
|
|
|
data[f.resolveKey(f.LevelKey, DefaultKeyLevel)] = entry.Level.String()
|
2014-07-27 05:26:04 +04:00
|
|
|
|
2014-12-10 05:53:40 +03:00
|
|
|
serialized, err := json.Marshal(data)
|
2014-03-11 03:22:08 +04:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
|
|
|
}
|
|
|
|
return append(serialized, '\n'), nil
|
|
|
|
}
|
2016-11-17 22:28:41 +03:00
|
|
|
|
|
|
|
func (f *JSONFormatter) resolveKey(key, defaultKey string) string {
|
|
|
|
if len(key) > 0 {
|
|
|
|
return key
|
|
|
|
}
|
|
|
|
return defaultKey
|
|
|
|
}
|