How to implement level based logging in golang?

前端 未结 11 2111
谎友^
谎友^ 2020-12-24 04:44

Is there any good wrapper available for level based logging in golang? If not, how should I go about implementing one myself?

What I want is pretty simple. I want a

11条回答
  •  天涯浪人
    2020-12-24 05:15

    One of the logging module that you can consider is klog . It support 'V' logging which gives the flexibility to log at certain level

    klog is a fork of glog and overcomes following drawbacks

    glog presents a lot "gotchas" and introduces challenges in containerized environments, all of which aren't well documented. glog doesn't provide an easy way to test logs, which detracts from the stability of software using it glog is C++ based and klog is a pure golang implementation

    Sample Implementation

    package main
    
    import (
        "flag"
    
        "k8s.io/klog"
    
    
    )
    
    type myError struct {
        str string
    }
    
    func (e myError) Error() string {
        return e.str
    }
    
    func main() {
        klog.InitFlags(nil)
        flag.Set("v", "1")
        flag.Parse()
    
        klog.Info("hello", "val1", 1, "val2", map[string]int{"k": 1})
        klog.V(3).Info("nice to meet you")
        klog.Error(nil, "uh oh", "trouble", true, "reasons", []float64{0.1, 0.11, 3.14})
        klog.Error(myError{"an error occurred"}, "goodbye", "code", -1)
        klog.Flush()
    }
    

提交回复
热议问题