Skip to content

liuliqiang/log4go

Repository files navigation

log4go

Go Report Card GoDoc codecov Sourcegraph Open Source Helpers Release TODOs

A log library for golang based on hashicorp/logutils

Why log4go

Yes, it another logging library for Go program language. Why do I create a new logging library for Go when there are so many popular logging library. such as:

For my daily use, i found several points are important for logging:

  • level for logging shoud be easy to use
  • content for logging should be friendly for human reading
  • logs should be easy to check

so i create log4go

Quick start

  1. Step 01: get the library

    $ go get -u github.com/liuliqiang/log4go
    
  2. Step 02: try in code:

    func main() {
    	log4go.Debug("I am debug log")
    	log4go.Info("Web server is started at %s:%d", "127.0.0.1", 80)
    	log4go.Warn("Get an empty http request")
    	log4go.Error("Failed to query record from db: %v", errors.New("db error"))
    }
    
  3. Step 03: Run it!

    $ go run main.go
    2019/08/10 00:02:18 [INFO]Web server is started at 127.0.0.1:80
    2019/08/10 00:02:18 [WARN]Get an empty http request
    2019/08/10 00:02:18 [EROR]Failed to query record from db: db error
    

Dynamic change log level

Just add a endpoint(such as http/grpc/...) to change log level such as:

http.HandleFunc("/logs", func(resp http.ResponseWriter, req *http.Request) {
	switch req.URL.Query()["level"][0] {
	case "debug":
		log4go.SetLevel(log4go.LogLevelDebug)
	case "info":
		log4go.SetLevel(log4go.LogLevelInfo)
	case "warning":
		log4go.SetLevel(log4go.LogLevelWarn)
	case "error":
		log4go.SetLevel(log4go.LogLevelError)
	}
	return
})

Print caller file and line

For the default logger, call SetWithCaller:

log4go.SetWithCaller(true)
log4go.Error("something failed")
// 2019/08/10 00:02:18 [EROR][main.go:42]something failed

For a named logger, set WithCaller in LoggerOpts:

logger := log4go.NewLogger("myapp", &log4go.LoggerOpts{WithCaller: true})
logger.Error(ctx, "something failed")
// 2019/08/10 00:02:18 myapp[EROR][main.go:42]something failed

It also works together with fields and request ID:

logger := log4go.NewLogger("myapp", &log4go.LoggerOpts{
    WithCaller: true,
    WithId:     true,
    IdName:     "x-request-id",
})
logger = logger.WithField("user", "alice")
logger.Error(ctx, "query failed")
// 2019/08/10 00:02:18 myapp[EROR][main.go:42][req-123][user=alice]query failed

Learn more...

About

A log library for golang based on hashicorp/logutils

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages