5
0
mirror of https://github.com/cwinfo/matterbridge.git synced 2024-11-10 08:40:29 +00:00
matterbridge/vendor/github.com/sirupsen/logrus/json_formatter.go

80 lines
1.8 KiB
Go
Raw Normal View History

2016-04-10 21:39:38 +00:00
package logrus
import (
"encoding/json"
"fmt"
)
2017-03-25 19:45:10 +00:00
type fieldKey string
2018-02-20 22:41:09 +00:00
// FieldMap allows customization of the key names for default fields.
2017-03-25 19:45:10 +00:00
type FieldMap map[fieldKey]string
2018-02-20 22:41:09 +00:00
// Default key names for the default fields
2017-03-25 19:45:10 +00:00
const (
FieldKeyMsg = "msg"
FieldKeyLevel = "level"
FieldKeyTime = "time"
)
func (f FieldMap) resolve(key fieldKey) string {
if k, ok := f[key]; ok {
return k
}
return string(key)
}
2018-02-20 22:41:09 +00:00
// JSONFormatter formats logs into parsable json
2016-04-10 21:39:38 +00:00
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
TimestampFormat string
2017-03-25 19:45:10 +00:00
// DisableTimestamp allows disabling automatic timestamps in output
DisableTimestamp bool
2018-02-20 22:41:09 +00:00
// FieldMap allows users to customize the names of keys for default fields.
2017-03-25 19:45:10 +00:00
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
2018-02-20 22:41:09 +00:00
// FieldKeyMsg: "@message",
2017-03-25 19:45:10 +00:00
// },
// }
FieldMap FieldMap
2016-04-10 21:39:38 +00:00
}
2018-02-20 22:41:09 +00:00
// Format renders a single log entry
2016-04-10 21:39:38 +00:00
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+3)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
2018-02-20 22:41:09 +00:00
// https://github.com/sirupsen/logrus/issues/137
2016-04-10 21:39:38 +00:00
data[k] = v.Error()
default:
data[k] = v
}
}
prefixFieldClashes(data)
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
2018-02-20 22:41:09 +00:00
timestampFormat = defaultTimestampFormat
2016-04-10 21:39:38 +00:00
}
2017-03-25 19:45:10 +00:00
if !f.DisableTimestamp {
data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
}
data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
2016-04-10 21:39:38 +00:00
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}