log/formatter_json.go
2024-01-03 21:25:52 +01:00

71 lines
1.7 KiB
Go

// Copyright 2023 Martin Riedl
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package golog
import (
"encoding/json"
"log"
"time"
)
type FormatterJSON struct {
FlatContent bool
TimeFormat string
data map[string]interface{}
}
func NewFormatterJSON() *FormatterJSON {
return &FormatterJSON{
TimeFormat: time.RFC3339,
}
}
func (formatter *FormatterJSON) Begin(entry *Entry) {
// reset formatter
formatter.data = make(map[string]interface{})
// add timestamp
formatter.data["time"] = entry.Time.Format(formatter.TimeFormat)
// add log level
formatter.data["level"] = entry.Level.String()
}
func (formatter *FormatterJSON) Process(entry *Entry) {
// add message
formatter.data["message"] = entry.Message
// add additional fields
if formatter.FlatContent {
for _, content := range entry.Content {
formatter.data[content.Key] = content.Value
}
} else {
formatter.data["fields"] = entry.Content
}
}
func (formatter *FormatterJSON) End(entry *Entry) []byte {
// build JSON
data, err := json.Marshal(formatter.data)
if err != nil {
// marshal should never fail
log.Println(err)
return []byte{}
}
// return json data
return data
}