shicky
shicky

Reputation: 1249

Golang logging strategy

Standard log package in Go does not support levels unlike logging standard library in Python.

Many packages resort to third-party log packages such as glog or logrus.

What is best logging strategy for Go when importing third-party packages that may or may not use third-party logging package.

Upvotes: 1

Views: 2168

Answers (1)

vogtb
vogtb

Reputation: 452

So, I think you're asking, what if a package I'm using uses plain old https://golang.org/pkg/log/ and my main package uses something special, like log.Info, log.Warn, log.Error, and log.Debug?

If the package exposes the log.Logger object to you, you can use SetFlags, SetOutput, SetPrefix to alter what those log messages look like, or silence them altogether, but you can't make them play nice with your special third-party logging package.

For example if a third part package looks like this:

package sayhello

import (
      "log"
      "os"
)

type SayHello {
      Logger *log.Logger
}

func NewSayHello() (SayHello) {
      logger, _ := os.OpenFile("/tmp/tmp.log",  os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
      var sh SayHello
      sh.Logger = log.New(logger, "SAY HELLO LOGGER: ", log.Ldate|log.Ltime|log.Lshortfile)
      return sh
}

func (sh SayHello) Run() {
      sh.Logger.Println("Hello. I ran!")
}

Then I can silence it like this:

package main

import (
      "sayhello"
      "io/ioutil"
)

func main() {
      sh := sayhello.NewSayHello()
      sh.Run()
      // output is: 2016/08/10 16:47:46 SAY HELLO LOGGER: Hello. I ran!
      sh.Logger.SetOutput(ioutil.Discard)
      sh.Run()
      // output is nothing
}

But there's really no way you can translate log statements in another package like log.Println in a into something like log.Info, or log.Debug, which is what you're looking for.

Upvotes: 2

Related Questions