package logrus
import (
"bytes"
"encoding/json"
"fmt"
"runtime"
)
type fieldKey string
type FieldMap map [fieldKey ]string
func (f FieldMap ) resolve (key fieldKey ) string {
if k , ok := f [key ]; ok {
return k
}
return string (key )
}
type JSONFormatter struct {
TimestampFormat string
DisableTimestamp bool
DisableHTMLEscape bool
DataKey string
FieldMap FieldMap
CallerPrettyfier func (*runtime .Frame ) (function string , file string )
PrettyPrint bool
}
func (f *JSONFormatter ) Format (entry *Entry ) ([]byte , error ) {
data := make (Fields , len (entry .Data )+4 )
for k , v := range entry .Data {
switch v := v .(type ) {
case error :
data [k ] = v .Error()
default :
data [k ] = v
}
}
if f .DataKey != "" {
newData := make (Fields , 4 )
newData [f .DataKey ] = data
data = newData
}
prefixFieldClashes (data , f .FieldMap , entry .HasCaller ())
timestampFormat := f .TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if entry .err != "" {
data [f .FieldMap .resolve (FieldKeyLogrusError )] = entry .err
}
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 ()
if entry .HasCaller () {
funcVal := entry .Caller .Function
fileVal := fmt .Sprintf ("%s:%d" , entry .Caller .File , entry .Caller .Line )
if f .CallerPrettyfier != nil {
funcVal , fileVal = f .CallerPrettyfier (entry .Caller )
}
if funcVal != "" {
data [f .FieldMap .resolve (FieldKeyFunc )] = funcVal
}
if fileVal != "" {
data [f .FieldMap .resolve (FieldKeyFile )] = fileVal
}
}
var b *bytes .Buffer
if entry .Buffer != nil {
b = entry .Buffer
} else {
b = &bytes .Buffer {}
}
encoder := json .NewEncoder (b )
encoder .SetEscapeHTML (!f .DisableHTMLEscape )
if f .PrettyPrint {
encoder .SetIndent ("" , " " )
}
if err := encoder .Encode (data ); err != nil {
return nil , fmt .Errorf ("failed to marshal fields to JSON, %w" , err )
}
return b .Bytes (), nil
}
The pages are generated with Golds v0.3.6 . (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .