Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use debug log in golang

Tags:

go

I’ve 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

https://github.com/Sirupsen/logrus
https://github.com/uber-go/zap

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 Im new to golfing .

like image 256
Jenny Hilton Avatar asked Nov 27 '17 15:11

Jenny Hilton


2 Answers

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

like image 152
Elias Van Ootegem Avatar answered Oct 05 '22 15:10

Elias Van Ootegem


If the only thing you need is check level before printing you can create you own thin wrapper for standard logger.

This will help to better understand how they work. Feel free to ask any questions.

package main

import (
    "log"
)

type MyLog struct {
    PrintDebug bool
}

func (m *MyLog) Debug(args ...interface{}) {
    if m.PrintDebug {
        m.Print(args...)
    }
}

func (m *MyLog) Print(args ...interface{}) {
    log.Print(args...)
}

func main() {
    ml := MyLog{}
    ml.Debug("PrintDebig = false, so no oitput")
    ml.Print("this will be printed anyway")

    ml.PrintDebug = true
    ml.Debug("Hello, playground")
}

https://play.golang.org/p/gKxQtC9NqX

like image 33
Eugene Lisitsky Avatar answered Oct 05 '22 14:10

Eugene Lisitsky