• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang logrus.WithFields函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/Sirupsen/logrus.WithFields函数的典型用法代码示例。如果您正苦于以下问题:Golang WithFields函数的具体用法?Golang WithFields怎么用?Golang WithFields使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了WithFields函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: GetToken

// GetToken wraps the incoming username into a TokenStruct, serializes the result to json
// and generates a Fernet token based on the resulting string
func GetToken(username string) string {
	// If the configuration has changed, re-load the keys
	if confVersion != util.GetConfig().Version {
		loadMintKey()
	}

	claims := jwt.StandardClaims{
		Issuer:    "FoxAuthn",
		Subject:   username,
		IssuedAt:  time.Now().Unix(),
		ExpiresAt: time.Now().Add(time.Duration(util.GetConfig().Authn.TokenTTL) * time.Second).Unix(),
	}

	log.WithFields(log.Fields{
		"claims": claims,
	}).Debug("Going to sign with these claims")

	token := jwt.NewWithClaims(jwt.SigningMethodRS384, claims)
	ss, err := token.SignedString(GetKey())
	if err != nil {
		log.WithFields(log.Fields{
			"path": mint.From,
		}).Panic("Failed to create signed token: ", err)
	}
	return ss
}
开发者ID:e-gov,项目名称:fox,代码行数:28,代码来源:Mint.go


示例2: newRepo

func newRepo(name string, simpleDocker SimpleDocker.SimpleDocker) (Repo, error) {
	log.WithFields(log.Fields{
		"name": name,
	}).Info("Creating new repo")

	r := Repo{
		Name:         name,
		SimpleDocker: simpleDocker,
	}

	startTime := time.Now()
	repoName := fmt.Sprintf("ihsw/%s", name)
	if err := r.pullImage(repoName); err != nil {
		log.WithFields(log.Fields{
			"name":     name,
			"err":      err.Error(),
			"repoName": repoName,
		}).Warn("Could not pull image")

		return Repo{}, err
	}

	log.WithFields(log.Fields{
		"name":     name,
		"duration": fmt.Sprintf("%v", time.Now().Sub(startTime)),
	}).Info("Repo create success")

	return r, nil
}
开发者ID:galactic-filament,项目名称:the-matrix,代码行数:29,代码来源:Repo.go


示例3: main

func main() {
	var (
		accessToken = kingpin.Flag("access-token", "GitHub access token").Required().PlaceHolder("TOKEN").String()
		owner       = kingpin.Flag("owner", "GitHub repository owner whose pull requests will be operated upon").Required().PlaceHolder("OWNER").String()
		repository  = kingpin.Flag("repository", "GitHub repository name whose pull requests will be operated upon").Required().PlaceHolder("REPO").String()
		label       = kingpin.Flag("label", "Name of a label used on the pull request to indicate that it has automatically been closed").PlaceHolder("LABEL").String()
		comment     = kingpin.Flag("comment", "Content of comment, which will be created when pull request is closed").PlaceHolder("TEXT").Default("Pull request was automatically closed").String()
		days        = kingpin.Flag("days", "Integer number of days. If at least this number of days elapses after a pull request has been created without any new comment or commits being posted it will be closed and an explanatory comment will be posted").Required().PlaceHolder("LABEL").Int()
	)

	kingpin.UsageTemplate(kingpin.CompactUsageTemplate)
	kingpin.CommandLine.Help = "Tool to auto-close old GitHub pull requests that were forgotten by their committer"
	kingpin.Parse()

	p := NewPullRequestCloser(*accessToken)

	pullRequests, err := p.findPullRequests(*owner, *repository, *days)
	if err != nil {
		log.WithFields(log.Fields{"error": err}).Fatal("Failed to find pull requests")
	}
	for _, pullRequest := range pullRequests {
		log.WithFields(log.Fields{"pull_request": *pullRequest.HTMLURL}).Info("Closing pull request")
		err = p.closePullRequest(*owner, *repository, pullRequest, *comment, *label)
		if err != nil {
			log.WithFields(log.Fields{"error": err, "pull_request": *pullRequest.HTMLURL}).Warn("Failed to close pull request")
		}
	}
}
开发者ID:fstehle,项目名称:pull-request-closer,代码行数:28,代码来源:main.go


示例4: Start

// Start the link with the specified toxics
func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser) {
	go func() {
		bytes, err := io.Copy(link.input, source)
		if err != nil {
			logrus.WithFields(logrus.Fields{
				"name":     link.proxy.Name,
				"upstream": link.proxy.Upstream,
				"bytes":    bytes,
				"err":      err,
			}).Warn("Source terminated")
		}
		link.input.Close()
	}()
	for i, toxic := range link.toxics.chain {
		go link.stubs[i].Run(toxic)
	}
	go func() {
		bytes, err := io.Copy(dest, link.output)
		if err != nil {
			logrus.WithFields(logrus.Fields{
				"name":     link.proxy.Name,
				"upstream": link.proxy.Upstream,
				"bytes":    bytes,
				"err":      err,
			}).Warn("Destination terminated")
		}
		dest.Close()
		link.toxics.RemoveLink(name)
		link.proxy.RemoveConnection(name)
	}()
}
开发者ID:jpittis,项目名称:toxiproxy,代码行数:32,代码来源:link.go


示例5: generateTempSocketPath

func generateTempSocketPath(dir, prefix string) (string, error) {
	// Use TempFile to allocate a uniquely named file in either the specified
	// dir or the default temp dir. It is then removed so that the unix socket
	// can be created with that name.
	// TODO: Decide on permissions
	if dir != "" {
		if err := os.MkdirAll(dir, os.ModePerm); err != nil {
			log.WithFields(log.Fields{
				"directory": dir,
				"perm":      os.ModePerm,
				"error":     err,
			}).Error("failed to create directory for socket")
			return "", err
		}
	}

	f, err := ioutil.TempFile(dir, prefix)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Error("failed to create temp file for response socket")
		return "", err
	}
	_ = f.Close()
	_ = os.Remove(f.Name())

	return fmt.Sprintf("%s.sock", f.Name()), nil
}
开发者ID:mistifyio,项目名称:acomm,代码行数:28,代码来源:tracker.go


示例6: connect

func (f *forwarder) connect() {
	if f.c != nil {
		return
	}

	rate := time.Tick(200 * time.Millisecond)
	for {
		var c net.Conn
		var err error

		if f.Config.TlsConfig != nil {
			c, err = tls.Dial("tcp", f.Config.ForwardDest, f.Config.TlsConfig)
		} else {
			c, err = net.DialTimeout("tcp", f.Config.ForwardDest, f.Config.ForwardDestConnectTimeout)
		}

		if err != nil {
			f.cErrors.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "message": err}).Error("Forwarder Connection Error")
			f.disconnect()
		} else {
			f.cSuccesses.Inc(1)
			log.WithFields(log.Fields{"id": f.ID, "remote_addr": c.RemoteAddr().String()}).Info("Forwarder Connection Success")
			f.c = c
			return
		}
		<-rate
	}
}
开发者ID:heroku,项目名称:log-iss,代码行数:29,代码来源:forwarder.go


示例7: LoadMintKeyByName

// loadMintKeyByName loads a key by filename and stores it in the struct
// The function is threadsafe and panics if the key file is invalid
func LoadMintKeyByName(filename string) {

	keyPath := util.GetPaths([]string{filename})[0]

	b, err := ioutil.ReadFile(keyPath)

	if err != nil {
		log.WithFields(log.Fields{
			"path": keyPath,
		}).Panic("Failed to load mint key: ", err)
	}

	k, err := jwt.ParseRSAPrivateKeyFromPEM(b)
	if err != nil {
		log.WithFields(log.Fields{
			"path": keyPath,
		}).Panic("Failed to parse mint key: ", err)
	}

	log.WithFields(log.Fields{
		"path": keyPath,
	}).Debugf("Successfully loaded mint key from %s", keyPath)
	// Store only after we are sure loading was good

	mint.Lock()
	defer mint.Unlock()
	mint.Key = k
	mint.From = keyPath
}
开发者ID:e-gov,项目名称:fox,代码行数:31,代码来源:Mint.go


示例8: handleRouteRefresh

func (peer *Peer) handleRouteRefresh(e *FsmMsg) []*table.Path {
	m := e.MsgData.(*bgp.BGPMessage)
	rr := m.Body.(*bgp.BGPRouteRefresh)
	rf := bgp.AfiSafiToRouteFamily(rr.AFI, rr.SAFI)
	if _, ok := peer.fsm.rfMap[rf]; !ok {
		log.WithFields(log.Fields{
			"Topic": "Peer",
			"Key":   peer.ID(),
			"Data":  rf,
		}).Warn("Route family isn't supported")
		return nil
	}
	if _, ok := peer.fsm.capMap[bgp.BGP_CAP_ROUTE_REFRESH]; !ok {
		log.WithFields(log.Fields{
			"Topic": "Peer",
			"Key":   peer.ID(),
		}).Warn("ROUTE_REFRESH received but the capability wasn't advertised")
		return nil
	}
	rfList := []bgp.RouteFamily{rf}
	peer.adjRibOut.Drop(rfList)
	accepted, filtered := peer.getBestFromLocal(rfList)
	peer.adjRibOut.Update(accepted)
	for _, path := range filtered {
		path.IsWithdraw = true
		accepted = append(accepted, path)
	}
	return accepted
}
开发者ID:karamsivia,项目名称:netplugin,代码行数:29,代码来源:peer.go


示例9: makeHeloChecker

func makeHeloChecker(sendLimiter *rerate.Limiter, spamLimiter *rerate.Limiter) func(smtpd.Peer, string) error {
	return func(peer smtpd.Peer, heloName string) error {
		if err := sendLimiter.Inc(heloName); err != nil {
			log.WithFields(log.Fields{
				"heloName": heloName,
				"error":    err,
			}).Warn("Can't increment send")
		}

		if exc, _ := sendLimiter.Exceeded(heloName); exc {
			log.WithFields(log.Fields{
				"rateLimit": "send",
				"peer":      peer,
			}).Warn("rateLimit exceeded")
			return smtpd.Error{Code: 451, Message: "Rate Limit exceeded"}
		}
		if exc, _ := spamLimiter.Exceeded(heloName); exc {
			log.WithFields(log.Fields{
				"rateLimit": "spam",
				"peer":      peer,
			}).Warn("rateLimit exceeded")
			return smtpd.Error{Code: 451, Message: "Rate Limit exceeded"}
		}
		return nil
	}
}
开发者ID:themecloud,项目名称:heimdall,代码行数:26,代码来源:mail.go


示例10: ValidateDeletePeer

// ValidateDeletePeer is the validation function for DeletePeer to invoke the rpc
// server call
func ValidateDeletePeer(remoteAddress string, id string) (*PeerGenericResp, error) {
	args := &PeerDeleteReq{ID: id}

	rpcConn, e := grpc.Dial(remoteAddress, grpc.WithInsecure())
	if e != nil {
		log.WithFields(log.Fields{
			"error":  e,
			"remote": remoteAddress,
		}).Error("failed to grpc.Dial remote")
		rsp := &PeerGenericResp{
			OpRet:   -1,
			OpError: e.Error(),
		}
		return rsp, e
	}
	defer rpcConn.Close()

	client := NewPeerServiceClient(rpcConn)

	rsp, e := client.ValidateDelete(netctx.TODO(), args)
	if e != nil {
		log.WithFields(log.Fields{
			"error":  e,
			"rpc":    "PeerService.ValidateDelete",
			"remote": remoteAddress,
		}).Error("failed RPC call")
		rsp := &PeerGenericResp{
			OpRet:   -1,
			OpError: e.Error(),
		}
		return rsp, e
	}
	return rsp, nil
}
开发者ID:kshlm,项目名称:glusterd2,代码行数:36,代码来源:peer-rpc-clnt.go


示例11: ConfigureRemoteETCD

// ConfigureRemoteETCD will reconfigure etcd server on remote node to either
// join or remove itself from an etcd cluster.
func ConfigureRemoteETCD(remoteAddress string, args *EtcdConfigReq) (*PeerGenericResp, error) {

	rpcConn, e := grpc.Dial(remoteAddress, grpc.WithInsecure())
	if e != nil {
		log.WithFields(log.Fields{
			"error":  e,
			"remote": remoteAddress,
		}).Error("failed to grpc.Dial remote")
		rsp := &PeerGenericResp{
			OpRet:   -1,
			OpError: e.Error(),
		}
		return rsp, e
	}
	defer rpcConn.Close()

	client := NewPeerServiceClient(rpcConn)

	rsp, e := client.ExportAndStoreETCDConfig(netctx.TODO(), args)
	if e != nil {
		log.WithFields(log.Fields{
			"error":  e,
			"rpc":    "PeerService.ExportAndStoreETCDConfig",
			"remote": remoteAddress,
		}).Error("failed RPC call")
		rsp := &PeerGenericResp{
			OpRet:   -1,
			OpError: e.Error(),
		}
		return rsp, e
	}
	return rsp, nil
}
开发者ID:kshlm,项目名称:glusterd2,代码行数:35,代码来源:peer-rpc-clnt.go


示例12: Serve

// Serve starts DNS server
func (dns *DNS) Serve(net string) (err error) {
	log.WithFields(log.Fields{
		"service": "dns",
		"net":     net,
	}).Info("Serve over ", net)

	dns.Server = &mdns.Server{
		Addr: fmt.Sprintf("%s:%d", dns.Config.DNS.IP, dns.Config.DNS.Port),
		Net:  net,
	}

	mdns.HandleFunc(".", dns.HandleRequest)

	err = dns.Server.ListenAndServe()
	if err != nil {
		log.WithFields(log.Fields{
			"service": "dns",
			"addr":    dns.Config.DNS.IP,
			"port":    dns.Config.DNS.Port,
			"net":     net,
			"error":   err,
		}).Error("Can't start server")
	}
	defer dns.Server.Shutdown()

	log.WithFields(log.Fields{
		"service": "dns",
	}).Info("[dns] Shutdown...")

	return
}
开发者ID:parkomat,项目名称:parkomat,代码行数:32,代码来源:dns.go


示例13: configGet

func configGet(c *cli.Context) {
	arg := c.Args().Get(0)
	if arg == "" {
		return
	}

	cfg, err := config.LoadConfig()
	if err != nil {
		log.WithFields(log.Fields{"err": err}).Fatal("config get: failed to load config")
	}

	val, err := cfg.Get(arg)
	if err != nil {
		log.WithFields(log.Fields{"cfg": cfg, "key": arg, "val": val, "err": err}).Fatal("config get: failed to retrieve value")
	}

	printYaml := false
	switch val.(type) {
	case []interface{}:
		printYaml = true
	case map[interface{}]interface{}:
		printYaml = true
	}

	if printYaml {
		bytes, err := yaml.Marshal(val)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(bytes))
	} else {
		fmt.Println(val)
	}
}
开发者ID:Jdesk,项目名称:os,代码行数:34,代码来源:config.go


示例14: main

func main() {
	err := jq.Init()
	if err != nil {
		log.Fatal(err)
	}

	log.WithFields(log.Fields{
		"version": jq.Version,
		"path":    jq.Path,
	}).Info("initialized jq")

	conf, err := config.Load()
	if err != nil {
		log.Fatal(err)
	}

	log.WithFields(log.Fields{
		"host": conf.Host,
		"port": conf.Port,
	}).Infof("Starting server at %s:%s", conf.Host, conf.Port)
	srv := server.New(conf)
	err = srv.Start()
	if err != nil {
		log.WithError(err).Fatal("error starting sever")
	}
}
开发者ID:jingweno,项目名称:jqplay,代码行数:26,代码来源:main.go


示例15: startInterruptHandling

func startInterruptHandling(modules ...coreModule) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)

	//Let's block until someone tells us to quit
	go func() {
		sig := <-c
		log.WithFields(
			log.Fields{
				"block":   "main",
				"_module": "snapd",
			}).Info("shutting down modules")

		for _, m := range modules {
			log.WithFields(
				log.Fields{
					"block":       "main",
					"_module":     "snapd",
					"snap-module": m.Name(),
				}).Info("stopping module")
			m.Stop()
		}
		log.WithFields(
			log.Fields{
				"block":   "main",
				"_module": "snapd",
				"signal":  sig.String(),
			}).Info("exiting on signal")
		os.Exit(0)
	}()
}
开发者ID:jcooklin,项目名称:snap,代码行数:31,代码来源:snapd.go


示例16: Stream

// Stream streams data from a URL to a destination writer.
func Stream(dest io.Writer, addr *url.URL) error {
	if dest == nil {
		err := errors.New("missing dest")
		log.WithFields(log.Fields{
			"error": err,
		}).Error(err)
		return err
	}
	if addr == nil {
		err := errors.New("missing addr")
		log.WithFields(log.Fields{
			"error": err,
		}).Error(err)
		return err
	}

	switch addr.Scheme {
	case "unix":
		return streamUnix(dest, addr)
	case "http", "https":
		return streamHTTP(dest, addr)
	default:
		err := errors.New("unknown url type")
		log.WithFields(log.Fields{
			"error": err,
			"type":  addr.Scheme,
			"addr":  addr,
		}).Error("cannot stream from url")
		return err
	}
}
开发者ID:mistifyio,项目名称:acomm,代码行数:32,代码来源:stream.go


示例17: Run

func (d *Daemon) Run(oneShot bool, noop bool) int {
	d.oneShot = oneShot
	d.noop = noop
	if err := d.Setup(); err != nil {
		log.WithFields(log.Fields{"err": err.Error()}).Error("Error in initial setup")
		return 1
	}

	if !d.RouteTableManager.InstanceIsRouter(d.Instance) {
		log.WithFields(log.Fields{"instance_id": d.Instance}).Error("I am not a router (do not have src/destination checking disabled)")
		return 1
	}

	d.quitChan = make(chan bool, 1)
	err := d.RunRouteTables()
	if err != nil {
		log.WithFields(log.Fields{"err": err.Error()}).Error("Error in initial route table run")
		return 1
	}
	d.loopQuitChan = make(chan bool, 1)
	d.loopTimerChan = make(chan bool, 1)
	if oneShot {
		d.quitChan <- true
	} else {
		d.runHealthChecks()
		defer d.stopHealthChecks()
		d.RunSleepLoop()
	}
	<-d.quitChan
	d.loopQuitChan <- true
	return 0
}
开发者ID:somic,项目名称:AWSnycast,代码行数:32,代码来源:daemon.go


示例18: ChangeDirectory

func (pfs *physicalFS) ChangeDirectory(path string) error {
	var tmpDir string

	if pfs.homeRealDirectory == pfs.currentRealDirectory && path == ".." {
		return nil
	}

	if path[0] == '/' {
		// absolute path, join with homeDirectory
		tmpDir = filepath.Join(pfs.homeRealDirectory, path)
	} else {
		// relative path, join with currentDirectory
		tmpDir = filepath.Join(pfs.currentRealDirectory, path)
	}

	log.WithFields(log.Fields{"physicalFS": pfs, "tmpDir": tmpDir}).Debug("localFS::physicalFS::ChangeDirectory before testing tmpDir")

	// check existence and availability
	stat, err := os.Stat(tmpDir)
	if err != nil {
		log.WithFields(log.Fields{"physicalFS": pfs, "tmpDir": tmpDir}).Info("localFS::physicalFS::ChangeDirectory requested invalid directory")
		return err
	}

	if !stat.IsDir() {
		log.WithFields(log.Fields{"physicalFS": pfs, "tmpDir": tmpDir}).Info("localFS::physicalFS::ChangeDirectory requested entry is not a directory")
		return fmt.Errorf("%s requested entry is not a directory", path)
	}

	pfs.currentRealDirectory = tmpDir
	log.WithFields(log.Fields{"physicalFS": pfs}).Debug("localFS::physicalFS::ChangeDirectory before finish")
	return nil
}
开发者ID:MindFlavor,项目名称:ftpserver2,代码行数:33,代码来源:physicalFS.go


示例19: NewPrimary

// NewPrimary creates a new API router.
func NewPrimary(cluster cluster.Cluster, tlsConfig *tls.Config, status StatusHandler, enableCors bool) *mux.Router {
	// Register the API events handler in the cluster.
	eventsHandler := newEventsHandler()
	cluster.RegisterEventHandler(eventsHandler)

	context := &context{
		cluster:       cluster,
		eventsHandler: eventsHandler,
		statusHandler: status,
		tlsConfig:     tlsConfig,
	}

	r := mux.NewRouter()
	for method, mappings := range routes {
		for route, fct := range mappings {
			log.WithFields(log.Fields{"method": method, "route": route}).Debug("Registering HTTP route")

			localRoute := route
			localFct := fct
			wrap := func(w http.ResponseWriter, r *http.Request) {
				log.WithFields(log.Fields{"method": r.Method, "uri": r.RequestURI}).Debug("HTTP request received")
				if enableCors {
					writeCorsHeaders(w, r)
				}
				localFct(context, w, r)
			}
			localMethod := method

			r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(wrap)
			r.Path(localRoute).Methods(localMethod).HandlerFunc(wrap)
		}
	}

	return r
}
开发者ID:konder,项目名称:swarm,代码行数:36,代码来源:primary.go


示例20: AddLoadedMetricType

func (mc *metricCatalog) AddLoadedMetricType(lp *loadedPlugin, mt core.Metric) error {
	if err := validateMetricNamespace(mt.Namespace()); err != nil {
		log.WithFields(log.Fields{
			"_module": "control",
			"_file":   "metrics.go,",
			"_block":  "add-loaded-metric-type",
			"error":   fmt.Errorf("Metric namespace %s is invalid", mt.Namespace()),
		}).Error("error adding loaded metric type")
		return err
	}
	if lp.ConfigPolicy == nil {
		err := errors.New("Config policy is nil")
		log.WithFields(log.Fields{
			"_module": "control",
			"_file":   "metrics.go,",
			"_block":  "add-loaded-metric-type",
			"error":   err,
		}).Error("error adding loaded metric type")
		return err
	}
	newMt := metricType{
		Plugin:             lp,
		namespace:          mt.Namespace(),
		version:            mt.Version(),
		lastAdvertisedTime: mt.LastAdvertisedTime(),
		tags:               mt.Tags(),
		policy:             lp.ConfigPolicy.Get(mt.Namespace().Strings()),
		description:        mt.Description(),
		unit:               mt.Unit(),
	}
	mc.Add(&newMt)
	return nil
}
开发者ID:IRCody,项目名称:snap,代码行数:33,代码来源:metrics.go



注:本文中的github.com/Sirupsen/logrus.WithFields函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang logrus.Entry类代码示例发布时间:2022-05-28
下一篇:
Golang logrus.WithField函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap