mirror of
https://github.com/vbatts/go-mtree.git
synced 2024-11-27 02:25:40 +00:00
72ac04e7ca
With: $ git mv vendor/github.com/{S,s}irupsen $ sed -i 's/Sirupsen/sirupsen/g' $(git grep -l Sirupsen) catching up with the upstream lowercasing [1,2,3,4]. Because of the compatibility issues discussed in [3], some consumers may prefer to use the old uppercase version until they have time to update their other Logrus consumers to the new lowercase form. [1]: https://github.com/sirupsen/logrus/blame/v1.0.3/README.md#L6 [2]: https://github.com/sirupsen/logrus/pull/384 [3]: https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276 [4]: https://github.com/sirupsen/logrus/issues/553
79 lines
1.8 KiB
Go
79 lines
1.8 KiB
Go
package logrus
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
)
|
|
|
|
type fieldKey string
|
|
|
|
// FieldMap allows customization of the key names for default fields.
|
|
type FieldMap map[fieldKey]string
|
|
|
|
// Default key names for the default fields
|
|
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)
|
|
}
|
|
|
|
// JSONFormatter formats logs into parsable json
|
|
type JSONFormatter struct {
|
|
// TimestampFormat sets the format used for marshaling timestamps.
|
|
TimestampFormat string
|
|
|
|
// DisableTimestamp allows disabling automatic timestamps in output
|
|
DisableTimestamp bool
|
|
|
|
// FieldMap allows users to customize the names of keys for default fields.
|
|
// As an example:
|
|
// formatter := &JSONFormatter{
|
|
// FieldMap: FieldMap{
|
|
// FieldKeyTime: "@timestamp",
|
|
// FieldKeyLevel: "@level",
|
|
// FieldKeyMsg: "@message",
|
|
// },
|
|
// }
|
|
FieldMap FieldMap
|
|
}
|
|
|
|
// Format renders a single log entry
|
|
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`
|
|
// https://github.com/sirupsen/logrus/issues/137
|
|
data[k] = v.Error()
|
|
default:
|
|
data[k] = v
|
|
}
|
|
}
|
|
prefixFieldClashes(data)
|
|
|
|
timestampFormat := f.TimestampFormat
|
|
if timestampFormat == "" {
|
|
timestampFormat = defaultTimestampFormat
|
|
}
|
|
|
|
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()
|
|
|
|
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
|
|
}
|