8

Here below is the entry point of my web application written in Go using Labstack's Echo:

package main

import (
    "github.com/labstack/echo"
    mw "github.com/labstack/echo/middleware"
)

func main() {
    controller := controllers.NewUserController(getSession())

    app := echo.New()

    app.Use(mw.Logger())
    app.Use(mw.Recover())
    app.SetDebug(true)

    app.Post("/users", controller.CreateUser)
    app.Get("/users", controller.ListUsers)
    app.Get("/users/:id", controller.GetUser)
    app.Patch("/users/:id", controller.UpdateUser)
    app.Delete("/users/:id", controller.DeleteUser)

    app.Run(":8000")
}

How do I reuse the logging middleware instantiated in the Echo application? I've tried this:

package controllers

import (
    "net/http"

    "github.com/labstack/echo"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type (
    UserController struct {
        session *mgo.Session
    }
)

func NewUserController(s *mgo.Session) *UserController {
    return &UserController{s}
}

func (userController UserController) CreateUser(context *echo.Context) error {
    user := &models.User{}

    if err := context.Bind(user); err != nil {
        context.Echo().Logger().Error("Error creating user")
        return err
    }

    user.Id = bson.NewObjectId()

    userController.session.DB("test").C("users").Insert(user)
    context.Echo().Logger().Debug("Created user", id)

    return context.JSON(http.StatusCreated, user)
}

Even if the code above compiles, the statement

context.Echo().Logger().Debug("Created user", id)

doesn't produce any output... while the following statement does:

context.Echo().Logger().Info("Created user", id)

Am I missing something?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
j3d
  • 9,492
  • 22
  • 88
  • 172
  • 1
    The Logger seems to be an HTTP access_log logger. If you want to log manually, maybe you should try logger like [logrus](https://github.com/Sirupsen/logrus) – holys Mar 01 '16 at 13:52
  • @holys Although [the Logger middleware](https://echo.labstack.com/middleware/logger) is for it, [`echo.Logger`](https://echo.labstack.com/guide/customization) is not. – nekketsuuu Mar 24 '18 at 09:14

3 Answers3

8

I just started using Echo and don't know if anything has changed since this was posted, but I've found you can just import labstack's logger:

import "github.com/labstack/gommon/log"

Then use it:

log.Debug("Created user", id)
Dan 0
  • 914
  • 7
  • 15
  • It is used by [`echo.Logger`](https://echo.labstack.com/guide/customization#custom-logger) (see [this](https://github.com/labstack/echo/blob/60f88a7a1c4beaf04b6f9254c8d72b45a2ab161e/log.go)). – nekketsuuu Mar 24 '18 at 08:45
2

By Default echo uses "INFO" Log Level. So anything below "INFO" Level gets displayed.

If you want to see "DEBUG" Logs as well, You need to set the level to "DEBUG":

import "github.com/labstack/gommon/log"
e.Logger.SetLevel(log.DEBUG)

Hierarchy:

DEBUG
INFO
WARN
ERROR
OFF
vs4vijay
  • 1,175
  • 3
  • 14
  • 28
2

you can use 3rd party logging middleware such as https://github.com/sirupsen/logrus

import log "github.com/sirupsen/logrus"

example

create log entry function:

func makeLogEntry(c echo.Context) *log.Entry {
    if c == 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": c.Request().Method,
        "uri":    c.Request().URL.String(),
        "ip":     c.Request().RemoteAddr,
    })
}

then:

func middlewareLogging(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 = fmt.Sprintf("http error %d - %v", report.Code, report.Message)
    } else {
        report = echo.NewHTTPError(http.StatusInternalServerError, err.Error())
    }

    makeLogEntry(c).Error(report.Message)
    c.HTML(report.Code, report.Message.(string))
}

and then in main() function:

func main() {
    e := echo.New()

    e.Use(middlewareLogging)
    e.HTTPErrorHandler = errorHandler

    e.GET("/index", func(c echo.Context) error {
        return c.JSON(http.StatusOK, true)
    })

    lock := make(chan error)
    go func(lock chan error) {
        lock <- e.Start(":9000")
    }(lock)

    time.Sleep(1 * time.Millisecond)
    makeLogEntry(nil).Warning("application started without ssl/tls enabled")

    err := <-lock
    if err != nil {
        makeLogEntry(nil).Panic("failed to start application")
    }
}