Мне нужно создать собственный форматировщик logrus, а в Logrus Entry, похоже, нет поля с именем Buffer.
Я использую:
go версия go1.13.1 linux / amd64 https://github.com/sirupsen/logrus v0.10.0 Linux Cent OS 7
package util
import (
"bytes"
"encoding/json"
"strings"
"github.com/sirupsen/logrus"
)
type LogFormat struct {
TimestampFormat string
}
func (f *LogFormat) Format(entry *logrus.Entry) ([]byte, error) {
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
b.WriteByte('[')
b.WriteString(strings.ToUpper(entry.Level.String()))
b.WriteString("]:")
b.WriteString(entry.Time.Format(f.TimestampFormat))
if entry.Message != "" {
b.WriteString(" - ")
b.WriteString(entry.Message)
}
if len(entry.Data) > 0 {
b.WriteString(" || ")
}
for key, value := range entry.Data {
b.WriteString(key)
b.WriteByte('=')
b.WriteByte('{')
strValue, _ := json.Marshal(value)
var genericObject interface{}
json.Unmarshal(strValue, &genericObject)
b.WriteString(string(strValue))
b.WriteString("}, ")
}
b.WriteByte('\n')
return b.Bytes(), nil
}
Основная функция
package main
import (
"encoding/json"
"os"
"time"
"git-devops.totvs.com.br/rodrigo.henrique/logrusPeopleExample/data"
"git-devops.totvs.com.br/rodrigo.henrique/logrusPeopleExample/util"
"github.com/sirupsen/logrus"
)
func main() {
carlos := &data.People{
Name: "Carlos",
Age: 18,
LastSeen: time.Now(),
}
pedro := &data.People{
Name: "Pedro",
Age: 22,
Email: "pedro@email.com.br",
LastSeen: time.Now(),
}
json.NewEncoder(os.Stdout).Encode(
&carlos,
)
formatter := util.LogFormat{}
formatter.TimestampFormat = "2006-01-02 15:04:05"
logrus.SetFormatter(&formatter)
logrus.WithFields(logrus.Fields{
"people": &carlos,
}).Info("Logging ", carlos.Name)
logrus.WithFields(logrus.Fields{
"people": &pedro,
}).Info("Logging ", pedro.Name)
logrus.WithFields(logrus.Fields{
"people1": &pedro,
"people2": &carlos,
}).Info("Logging two people")
}
Во второй строке функции Format я получил ошибку, потому что в Entry нет поля Buffer.