如何在golang中使用调试日志

Jen*_*ton 3 go

我的应用程序应该使用登录状态的调试.即我想要提供的所有日志都像log.debug

我已经读过它并找到以下内容

https://github.com/Sirupsen/logrus
https://github.com/uber-go/zap
Run Code Online (Sandbox Code Playgroud)

我的问题是我应该如何"告诉"现在在调试模式下运行的程序然后将打印所有日志,因为我相信应该来自外部... 例如将是非常有用的,因为我是新手打高尔夫球.

Eli*_*gem 9

好的,我在评论中建议的一个非常简单的方法示例:

package main

import (
    "os"

    "github.com/sirupsen/logrus"
)

func init() {
    lvl, ok := os.LookupEnv("LOG_LEVEL")
    // LOG_LEVEL not set, let's default to debug
    if !ok {
        lvl = "debug"
    }
    // parse string, this is built-in feature of logrus
    ll, err := logrus.ParseLevel(lvl)
    if err != nil {
        ll = logrus.DebugLevel
    }
    // set global log level
    logrus.SetLevel(ll)
}

func main() {
    logrus.Debug("Will only be visible if the loglevel permits it")
}
Run Code Online (Sandbox Code Playgroud)

原评论:

检查那里的代码库.在go中,常见的方法是通过环境变量加载配置(例如LOG_LEVEL,并使用os.Getenv或配置包来加载值).这就是为什么logrus允许你通过int或字符串设置日志级别的原因.

请您:在提出问题之前,请阅读有关您使用的软件包的基本信息.甚至logrus的主自述文件的github repo也包含一个将日志级别设置为特定级别的示例:

https://github.com/sirupsen/logrus#example