go – Logrus Entry does not have Buffer field-ThrowExceptions

Exception or error:

I need to build a logrus custom formatter and Logrus Entry seems not have a field called Buffer.

I am using:

go version 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
}

Main Function

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")

}

In the second line of the Format function I’ve got an error because Entry does not have Buffer field.

How to solve:

logrus introduced Buffer in v0.11.0. You could use any version after v0.10.0.

But I would suggest to use the latest version [v1.4.2]. They must have added many functionalities and fixed issues in the later versions.

So, you should just use the latest version.

Leave a Reply

Your email address will not be published. Required fields are marked *