Logrus library go didn't formatted as well

158 views Asked by At

I use the logrus library for my logging purposes and my expectations are like the logs in the documentation, which are like this: Expected log

And this is my log while using logrus : My log

I've read through the documentation and followed the code what to do, but it still has no effect on my logs. This is the setup for the logs:

logger.middleware.go

package middleware

import (
    _ "fmt"
    "net/http"
    "time"

    "github.com/labstack/echo/v4"
    log "github.com/sirupsen/logrus"
)

func MakeLogEntry(echo echo.Context) *log.Entry {
    log.SetFormatter(&log.TextFormatter{
        FullTimestamp:   true,
        DisableColors:   true,
    })
    if echo == nil {
        return log.WithFields(
            log.Fields{
                "at": time.Now().Format("2006-01-02 15:04:05"),
            },
        )
    }

    return log.WithFields(
        log.Fields{
            "at":     time.Now().Format("2006-01-02 15:04:05"),
            "method": echo.Request().Method,
            "uri":    echo.Request().URL.String(),
            "ip":     echo.Request().RemoteAddr,
        },
    )
}

func LoggingRequest(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        MakeLogEntry(c).Info("Incoming request")

        return next(c)
    }
}

func ErrorHandler(err error, c echo.Context) {
    report, ok := err.(*echo.HTTPError)
    if ok {
        report.Message = map[string]interface{}{
            "error":       "HTTP Error",
            "message":     report.Message,
            "status code": report.Code,
        }
    } else {
        report = echo.NewHTTPError(http.StatusInternalServerError, err.Error())
    }

    MakeLogEntry(c).Error(report.Message)

    c.JSON(report.Code, report.Message.(map[string]interface{}))
}

Is there a setting I'm missing? or is there any code that should be added?

1

There are 1 answers

3
Sayed Khaidir Ali On

If you want to print log as the first picture with colorized log level, you just have to remove the block

log.SetFormatter(&log.TextFormatter{
        FullTimestamp:   true,
        DisableColors:   true,
    })

it's clear that you are using the TextFormatter which is not the default log format for logrus

Or if you want to segregate the color by log level, try to set DisableColors to false

Should you find my solution useful, please do upvote