Search code examples
gologging

How to use debug log in golang


I’ve an application which should use log in state of debug, i.e. all the logs that I want to provide is like log.debug

I’ve read about it and find the following

My question is how should I “tell” to the program that now run at debug mode an then all the logs will be printed since this I believe should come from outside …

example will be very helpful since I'm new to golfing.


Solution

  • Ok, a really simple example of the approach I suggested in the comment:

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

    The original comment:

    Check codebases that are out there. In go, the common way to do that is to load configuration via environment variables (eg LOG_LEVEL, and use os.Getenv or a config package to load the value). That's why logrus for example allows you to set log levels via ints or strings.

    Please, please: before you ask a question, read the basic info about the packages you use. Even the github repo for logrus' main README contains an example setting the log level to a specific level:

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