Logging Package in GoLang

On this post, I have added some of the collected notes on Logging by using Golang

Zap A logging package on golang from uber https://github.com/uber-go

Package zap provides fast, structured, leveled logging.

For applications that log in the hot path, reflection-based serialization and string formatting are prohibitively expensive – they’re CPU-intensive and make many small allocations. Put differently, using json.Marshal and fmt.Fprintf to log tons of interface{} makes your application slow.

Zap takes a different approach. It includes a reflection-free, zero-allocation JSON encoder, and the base Logger strives to avoid serialization overhead and allocations wherever possible. By building the high-level SugaredLogger on that foundation, zap lets users choose when they need to count every allocation and when they’d prefer a more familiar, loosely typed API.

https://godoc.org/go.uber.org/zap

Can’t say why it is better than others, Just tried with a quick example, will experiment more and write further updates here

Example :

package main
import (
   "fmt"
   "go.uber.org/zap"
   "time"
)
func main() {

   fmt.Println("SugaredLogger")

   sugar := zap.NewExample().Sugar()
   defer sugar.Sync()
   sugar.Infow("failed to fetch URL",
      "url", "http://example.com",
      "attempt", 3,
      "backoff", time.Second,
   )
   sugar.Infof("failed to fetch URL: %s", "http://example.com")


   fmt.Println("Logger")
   logger := zap.NewExample()
   defer logger.Sync()
   logger.Info("failed to fetch URL",
      zap.String("url", "http://example.com"),
      zap.Int("attempt", 3),
      zap.Duration("backoff", time.Second),
   )
}

Output:
SugaredLogger
{"level":"info","msg":"failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}
{"level":"info","msg":"failed to fetch URL: http://example.com"}
Logger
{"level":"info","msg":"failed to fetch URL","url":"http://example.com","attempt":3,"backoff":"1s"}

Refer :

https://www.client9.com/logging-packages-in-golang/

What package to use? These all work, but it all depends on what problem are you trying to solve.

  • For high volume (think: 100s or 1000s logs per second) or constrained devices (think Raspberry Pi): zap or zerolog.
  • To quickly replace all your crappy stdlib log calls to have a better output: sirupus, maybe apex
  • To exported logs to an existing system: logrus or apex/log
  • For pretty console applications: apex/log

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s