如何使用日志中间件

下面是我使用 Labstack 的 Echo 用 Go 编写的 Web 应用程序的入口点:


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

}

如何重用在Echo应用程序中实例化的日志中间件?我试过这个:


包控制器


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)

}

即使上面的代码编译通过,语句


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

不产生任何输出...而下面的语句呢:


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

我错过了什么吗?


一只萌萌小番薯
浏览 220回答 3
3回答

呼啦一阵风

我刚开始使用 Echo,不知道发布后是否有任何变化,但我发现您可以导入 labstack 的记录器:import "github.com/labstack/gommon/log"然后使用它:log.Debug("Created user", id)

慕桂英3389331

默认情况下,echo 使用“INFO”日志级别。所以任何低于“信息”级别的内容都会显示出来。如果您还想查看“DEBUG”日志,则需要将级别设置为“DEBUG”:import "github.com/labstack/gommon/log"e.Logger.SetLevel(log.DEBUG)等级制度:DEBUGINFOWARNERROROFF

慕森卡

您可以使用 3rd 方日志中间件,例如https://github.com/sirupsen/logrusimport log "github.com/sirupsen/logrus"例子创建日志条目功能:func makeLogEntry(c echo.Context) *log.Entry {&nbsp; &nbsp; if c == nil {&nbsp; &nbsp; &nbsp; &nbsp; return log.WithFields(log.Fields{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "at": time.Now().Format("2006-01-02 15:04:05"),&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; }&nbsp; &nbsp; return log.WithFields(log.Fields{&nbsp; &nbsp; &nbsp; &nbsp; "at":&nbsp; &nbsp; &nbsp;time.Now().Format("2006-01-02 15:04:05"),&nbsp; &nbsp; &nbsp; &nbsp; "method": c.Request().Method,&nbsp; &nbsp; &nbsp; &nbsp; "uri":&nbsp; &nbsp; c.Request().URL.String(),&nbsp; &nbsp; &nbsp; &nbsp; "ip":&nbsp; &nbsp; &nbsp;c.Request().RemoteAddr,&nbsp; &nbsp; })}然后:func middlewareLogging(next echo.HandlerFunc) echo.HandlerFunc {&nbsp; &nbsp; return func(c echo.Context) error {&nbsp; &nbsp; &nbsp; &nbsp; makeLogEntry(c).Info("incoming request")&nbsp; &nbsp; &nbsp; &nbsp; return next(c)&nbsp; &nbsp; }}func errorHandler(err error, c echo.Context) {&nbsp; &nbsp; report, ok := err.(*echo.HTTPError)&nbsp; &nbsp; if ok {&nbsp; &nbsp; &nbsp; &nbsp; report.Message = fmt.Sprintf("http error %d - %v", report.Code, report.Message)&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; report = echo.NewHTTPError(http.StatusInternalServerError, err.Error())&nbsp; &nbsp; }&nbsp; &nbsp; makeLogEntry(c).Error(report.Message)&nbsp; &nbsp; c.HTML(report.Code, report.Message.(string))}然后在 main() 函数中:func main() {&nbsp; &nbsp; e := echo.New()&nbsp; &nbsp; e.Use(middlewareLogging)&nbsp; &nbsp; e.HTTPErrorHandler = errorHandler&nbsp; &nbsp; e.GET("/index", func(c echo.Context) error {&nbsp; &nbsp; &nbsp; &nbsp; return c.JSON(http.StatusOK, true)&nbsp; &nbsp; })&nbsp; &nbsp; lock := make(chan error)&nbsp; &nbsp; go func(lock chan error) {&nbsp; &nbsp; &nbsp; &nbsp; lock <- e.Start(":9000")&nbsp; &nbsp; }(lock)&nbsp; &nbsp; time.Sleep(1 * time.Millisecond)&nbsp; &nbsp; makeLogEntry(nil).Warning("application started without ssl/tls enabled")&nbsp; &nbsp; err := <-lock&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; makeLogEntry(nil).Panic("failed to start application")&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go