简体   繁体   English

如何使用日志中间件

[英]How to use logging middleware

Here below is the entry point of my web application written in Go using Labstack's Echo:下面是我使用 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")
}

How do I reuse the logging middleware instantiated in the Echo application?如何重用在Echo应用程序中实例化的日志中间件? 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?我错过了什么吗?

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:我刚开始使用 Echo,不知道发布后是否有任何变化,但我发现您可以导入 labstack 的记录器:

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

Then use it:然后使用它:

log.Debug("Created user", id)

By Default echo uses "INFO" Log Level.默认情况下,echo 使用“INFO”日志级别。 So anything below "INFO" Level gets displayed.因此,“信息”级别以下的任何内容都会显示出来。

If you want to see "DEBUG" Logs as well, You need to set the level to "DEBUG":如果您还想查看“DEBUG”日志,则需要将级别设置为“DEBUG”:

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

Hierarchy:等级制度:

DEBUG
INFO
WARN
ERROR
OFF

you can use 3rd party logging middleware such as https://github.com/sirupsen/logrus您可以使用 3rd 方日志中间件,例如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:然后在 main() 函数中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM