gpt4 book ai didi

go - Logrus条目没有“缓冲区”字段

转载 作者:行者123 更新时间:2023-12-01 22:28:07 27 4
gpt4 key购买 nike

我需要构建一个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没有缓冲区字段。

最佳答案

logrusBuffer中引入了v0.11.0。您可以在v0.10.0之后使用任何版本。

但我建议使用最新版本[v1.4.2]。他们必须在更高版本中添加了许多功能并解决了问题。

因此,您应该只使用最新版本。

关于go - Logrus条目没有“缓冲区”字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58527585/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com