go-zookeeper客户端可选参数配置

 go-zookeeper有3个比较常用的可选参数,分别控制日志输出和事件回调:

//是否输出日志
func WithLogInfo(logInfo bool) connOption
//定制日志输出
func WithLogger(logger Logger) connOption
//事件回调
func WithEventCallback(cb EventCallback) connOption


 示例:

package main
 
import (
    "github.com/samuel/go-zookeeper/zk"
    "github.com/wonderivan/logger"
    "net/http"
    "runtime"
    "time"
)
 
type ZKLogger struct{}
 
func (lg ZKLogger) Printf(msg string, v ...interface{}) {
    logger.Info("zk: "+msg, v)
}
 
func main() {
    logger.SetLogger(`{"Console": {"level": "DEBG"}}`)
    logger.Info("version: " + runtime.Version())
 
    conn, _, _  := zk.Connect([]string{"127.0.0.1"},
        time.Second*5,
        zk.WithLogger(ZKLogger{}),
        zk.WithLogInfo(true),
        zk.WithEventCallback(zk.EventCallback(func(event zk.Event){
            logger.Info("zk event: Type=%v State=%v path=%s Server=%s Err=%s", event.Type, event.State,event.Path,event.Server,event.Err)
        })),
    )
    defer conn.Close()
 
    logger.Info("listen on 8080")
    http.ListenAndServe(":8080", nil)
}


 console日志输出:

2020-04-23 11:37:46 [INFO] [cms/zkoption.go:19] version: go1.13.8
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:31] listen on 8080
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:26] zk event: Type=EventSession State=StateConnecting path= Server=127.0.0.1:2181 Err=%!s(<nil>)
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:26] zk event: Type=EventSession State=StateConnected path= Server=127.0.0.1:2181 Err=%!s(<nil>)
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:14] zk: Connected to [127.0.0.1:2181]
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:26] zk event: Type=EventSession State=StateHasSession path= Server=127.0.0.1:2181 Err=%!s(<nil>)
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:14] zk: authenticated: id=[103690444943525257 5000], timeout=%!d(MISSING)
2020-04-23 11:37:46 [INFO] [cms/zkoption.go:14] zk: re-submitting `[0]` credentials after reconnect
 


————————————————
版权声明:本文为CSDN博主「pengpengzhou」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/pengpengzhou/article/details/105703602

相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:马嘣嘣 返回首页