[Go][Echo] Logging to file.

In Echo’s official document, describes about logging to stdout.

I want to write logs to file , so use Echo#Logger.SetOutput(io.Writer) .

package main
import (
    "net/http"
    "os"
    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
    "github.com/labstack/gommon/log"
)
func main() {
    e := echo.New()
    // Root Level Middleware
    // Logging
    e.Use(middleware.Logger())
    logfile, _ := os.OpenFile("debug.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    e.Logger.SetOutput(logfile)
    e.Logger.SetLevel(log.DEBUG)
    e.Logger.Debug("logging test.")
    e.GET("/", index)
    e.Logger.Fatal(e.Start(":1323"))
}
func index(c echo.Context) error {
    c.Echo().Logger.Debug("logging test on root : /")
    return c.String(http.StatusOK, "index page.")
}

Then start go run server.go and open localhost:[port] via browser.

log file results is bellow.

{"time":"2022-02-12T21:42:33.5192868+09:00","level":"DEBUG","prefix":"echo","file":"server.go","line":"20","message":"logging test."}
   ____    __
  / __/___/ /  ___
 / _// __/ _ \/ _ \
/___/\__/_//_/\___/ v4.6.3
High performance, minimalist Go web framework
https://echo.labstack.com
____________________________________O/_______
                                    O\
⇨ http server started on [::]:1323
{"time":"2022-02-12T21:42:40.810981+09:00","level":"DEBUG","prefix":"echo","file":"server.go","line":"27","message":"logging test on root : /"}
{"time":"2022-02-12T21:42:40.8110373+09:00","id":"","remote_ip":"::1","host":"localhost:1323","method":"GET","uri":"/","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36","status":200,"error":"","latency":72500,"latency_human":"72.5µs","bytes_in":0,"bytes_out":11}

Echo,GoEcho,Go,Logging

Posted by S