如何将日志消息保存到文件中(labstack/echo)

huangapple go评论136阅读模式
英文:

How to save log message to file (labstack/echo)

问题

我需要帮助..

我正在使用golang,目前我想将我的日志保存到日志文件中。我使用了echo框架进行日志记录,像这样:

e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
  Format: "method=${method}, uri=${uri}, status=${status}\n",
}))

有人知道如何将其保存到文件中吗?

英文:

I need help..

I am using golang, and currently I want to save my log into logger file. I used echo framework for logging, like this:

e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
  Format: "method=${method}, uri=${uri}, status=${status}\n",
}))

Does anyone knows How to save it into file?

答案1

得分: 1

LoggerConfigOutput字段是一个io.Writer类型。可以将任何实现了io.Writer接口的对象赋值给Output字段。

f, err := os.OpenFile("logfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
    panic(fmt.Sprintf("error opening file: %v", err))
}
defer f.Close()

// 中间件
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
    Format: "method=${method}, uri=${uri}, status=${status}\n",
    Output: f,
}))
英文:

Output field of LoggerConfig is io.Writer. Set to Output field any io.Writer implementation

f, err := os.OpenFile("logfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
	panic(fmt.Sprintf("error opening file: %v", err))
}
defer f.Close()

// Middleware
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
	Format: "method=${method}, uri=${uri}, status=${status}\n",
	Output: f,
}))

huangapple
  • 本文由 发表于 2021年11月3日 09:50:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/69818803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定