【问题标题】:Set logging level in glog package在 glog 包中设置日志记录级别
【发布时间】:2023-11-01 01:47:01
【问题描述】:

如何将 golang glog 包的日志记录级别设置为 ERROR。

example.go:

package main

import (
    "github.com/golang/glog"
    "flag"
)

func main() {
    flag.Parse()
    glog.Info("Info level")
    glog.Error("Error level")
    glog.Flush()
}
$ go run example.go -logtostderr=true -stderrthreshold=ERROR
I1214 15:46:00.743002   13429 example.go:10] Info level
E1214 15:46:00.743211   13429 example.go:11] Error level

在上面的示例中,我已将 stderrthreshold 标志设置为 ERROR,但仍会收到 INFO 级别的日志。我只想要 ERROR 级别的日志。

【问题讨论】:

  • glog 的级别在 V 上工作,而不是在 Info、Warning、Error 内容上。

标签: go logging error-logging glog


【解决方案1】:

默认情况下,glog 会写

  • 日志文件的所有日志消息(默认在/tmp创建);
  • 将严重性为stderrthreshold 或以上的消息记录到stderr。

通过使用-logtostderr=true 标志,此行为发生了变化:

日志写入标准错误而不是文件。

  • 没有日志消息写入日志文件;
  • 所有日志消息都写入标准错误。

stderrthreshold 可能在使用-logtostderr=true 时无效。而且在您的调用中它无论如何都没有效果,因为默认阈值已经是ERROR

总而言之,只需运行go run example.go 而不使用任何命令行参数,只有具有ERROR 或以上严重性的日志消息才会根据需要写入stderr。

【讨论】: