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

Golang logrus.Println函数代码示例

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

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



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

示例1: watch

func (c *consulCoordinator) watch(key string, cf consulFunc, stop chan struct{}) (chan interface{}, chan error) {
	new := make(chan interface{})
	errc := make(chan error)
	go func() {
		kv := c.client.KV()
		var lastIndex uint64
		for {
			select {
			case <-stop:
				return
			default:
				// do a blocking query
				ret, queryMeta, err := cf(kv, key, lastIndex)
				log.Println("[consul] value updated at", key, ret)
				if err != nil {
					log.Println(err)
					errc <- err
					return
				}
				if ret != nil {
					new <- ret
				}
				lastIndex = queryMeta.LastIndex
			}
		}
	}()
	return new, errc
}
开发者ID:nsaje,项目名称:dagger,代码行数:28,代码来源:consul.go


示例2: getPorts

func getPorts() ([]OsSerialPort, error) {
	resolver, err := bonjour.NewResolver(nil)
	if err != nil {
		log.Println("Failed to initialize resolver:", err.Error())
		return nil, err
	}

	results := make(chan *bonjour.ServiceEntry)

	timeout := make(chan bool, 1)
	go func(exitCh chan<- bool) {
		time.Sleep(timeoutConst * time.Second)
		exitCh <- true
		close(results)
	}(resolver.Exit)

	arrPorts := []OsSerialPort{}
	go func(results chan *bonjour.ServiceEntry, exitCh chan<- bool) {
		for e := range results {
			arrPorts = append(arrPorts, OsSerialPort{Name: e.AddrIPv4.String(), IdProduct: e.Instance, IdVendor: strings.Join(e.Text[:], " "), NetworkPort: true})
		}
		timeout <- true
	}(results, resolver.Exit)

	err = resolver.Browse("_arduino._tcp", "", results)
	if err != nil {
		log.Println("Failed to browse:", err.Error())
		return nil, err
	}
	// wait for some kind of timeout and return arrPorts
	select {
	case <-timeout:
		return arrPorts, nil
	}
}
开发者ID:matteosuppo,项目名称:arduino-create-agent,代码行数:35,代码来源:discovery.go


示例3: execCmd

// execCmd handles http requests received for the path "/exec"
func execCmd(w http.ResponseWriter, r *http.Request) {

	io.WriteString(w, "OK")

	go func() {
		cmd := r.URL.Query().Get("cmd")

		logrus.Info("got cmd: " + cmd)

		cmd, _ = url.QueryUnescape(cmd)
		arr := strings.Split(cmd, " ")

		logrus.Println("arr: ", arr)

		if len(arr) > 0 {
			cmd := exec.Command(arr[0], arr[1:]...)
			// Stdout buffer
			// cmdOutput := &bytes.Buffer{}
			// Attach buffer to command
			// cmd.Stdout = cmdOutput
			// Execute command
			// printCommand(cmd)
			err := cmd.Run() // will wait for command to return
			if err != nil {
				logrus.Println("Error:", err.Error())
			}
		}
	}()
}
开发者ID:stevesloka,项目名称:kubecraft,代码行数:30,代码来源:main.go


示例4: CreateSnapshot

func (d *driver) CreateSnapshot(
	runAsync bool,
	snapshotName, volumeID, description string) ([]*core.Snapshot, error) {

	resp, err := d.ec2Instance.CreateSnapshot(volumeID, description)
	if err != nil {
		return nil, err
	}

	if snapshotName != "" {
		_, err := d.ec2Instance.CreateTags(
			[]string{resp.Id}, []ec2.Tag{{"Name", snapshotName}})
		if err != nil {
			return nil, err
		}
	}

	if !runAsync {
		log.Println("Waiting for snapshot to complete")
		err = d.waitSnapshotComplete(resp.Snapshot.Id)
		if err != nil {
			return nil, err
		}
	}

	snapshot, err := d.GetSnapshot("", resp.Snapshot.Id, "")
	if err != nil {
		return nil, err
	}

	log.Println("Created Snapshot: " + snapshot[0].SnapshotID)
	return snapshot, nil

}
开发者ID:SebastianStadil,项目名称:rexray,代码行数:34,代码来源:ec2.go


示例5: initVars

func initVars() {

	done = make(chan int)

	resolvAddrs()

	password := flag.String("password", "0000", "Inverter password")
	groupType := flag.String("grouptype", "USER", "'USER' or 'INSTALLER'")
	server := flag.String("server", "tcp://notify.erkkila.org:1883", "The MQTT server to connect to")
	topic := flag.String("topic", "smapoller", "The chat room to enter. default 'smapoller'")
	name := flag.String("name", "pee", "Username to be displayed")

	flag.Parse()

	log.Println("SetP:", *password)
	log.Println("Gt:", *groupType)
	protocol.SetPassword(*password)
	protocol.SetGroupType(*groupType)
	protocol.SetAppSUSyID(AppSUSyID)
	protocol.SetAppSerial(getSerial())

	mqs = GetMQTTSettings()

	mqs.SetServer(server)
	mqs.SetTopic(topic)
	mqs.SetName(name)

}
开发者ID:pee,项目名称:smapoller,代码行数:28,代码来源:smapoller.go


示例6: writePacketLength

func writePacketLength(dst []byte) error {

	var LENGTH_OFFSET uint = 13
	var LENGTH_HEADER uint = 15
	var MAX_LENGTH uint = 0xFFFF

	if uint(len(dst)) < LENGTH_HEADER {
		log.Panic("Tried to set packet length to short buffer")
	}
	if uint(len(dst)) > MAX_LENGTH {
		log.Panic("Tried to set to big a packet length")
	}

	log.Println("Length of packet is:", len(dst))
	var length uint = uint(len(dst)) - (LENGTH_OFFSET + 7)
	log.Println("Setting packet length to:", length)

	l := make([]byte, 2)
	binary.LittleEndian.PutUint16(l, uint16(length))

	i := LENGTH_OFFSET
	dst[i] = l[0]
	i++
	dst[i] = l[1]

	return nil
}
开发者ID:pee,项目名称:smapoller,代码行数:27,代码来源:packetMaker.go


示例7: Delete

func (d *driver) Delete(volumeID api.VolumeID) error {
	v, err := d.GetVol(volumeID)
	if err != nil {
		logrus.Println(err)
		return err
	}

	bd, ok := d.buseDevices[v.DevicePath]
	if !ok {
		err = fmt.Errorf("Cannot locate a BUSE device for %s", v.DevicePath)
		logrus.Println(err)
		return err
	}

	// Clean up buse block file and close the NBD connection.
	os.Remove(bd.file)
	bd.f.Close()
	bd.nbd.Disconnect()

	logrus.Infof("BUSE deleted volume %v at NBD device %s", volumeID, v.DevicePath)

	err = d.DeleteVol(volumeID)
	if err != nil {
		logrus.Println(err)
		return err
	}

	return nil
}
开发者ID:pombredanne,项目名称:openstorage,代码行数:29,代码来源:buse.go


示例8: runWatcher

func runWatcher(address, datacenter, watchType string) {
	consulAlert := os.Args[0]
	cmd := exec.Command(
		"consul", "watch",
		"-http-addr", address,
		"-datacenter", datacenter,
		"-type", watchType,
		consulAlert, "watch", watchType)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Run(); err != nil {
		var exitCode int
		switch err.(type) {
		case *exec.ExitError:
			exitError, _ := err.(*exec.ExitError)
			status, _ := exitError.Sys().(syscall.WaitStatus)
			exitCode = status.ExitStatus()
			log.Println("Shutting down watcher --> Exit Code: ", exitCode)
		case *exec.Error:
			exitCode = 1
			log.Println("Shutting down watcher --> Something went wrong running consul watch: ", err.Error())
		default:
			exitCode = 127
			log.Println("Shutting down watcher --> Unknown error: ", err.Error())
		}
		os.Exit(exitCode)
	} else {
		log.Printf("Execution complete.")
	}
}
开发者ID:varunarya10,项目名称:consul-alerts,代码行数:31,代码来源:watchers.go


示例9: CmdList

func CmdList(databaseName string, page, pageSize int, id IDb, is services.IServices) error {
	service, err := is.RetrieveByLabel(databaseName)
	if err != nil {
		return err
	}
	if service == nil {
		return fmt.Errorf("Could not find a service with the label \"%s\". You can list services with the \"catalyze services\" command.", databaseName)
	}
	jobs, err := id.List(page, pageSize, service)
	if err != nil {
		return err
	}
	sort.Sort(SortedJobs(*jobs))
	for _, job := range *jobs {
		logrus.Printf("%s %s (status = %s)", job.ID, job.CreatedAt, job.Status)
	}
	if len(*jobs) == pageSize && page == 1 {
		logrus.Println("(for older backups, try with --page 2 or adjust --page-size)")
	}
	if len(*jobs) == 0 && page == 1 {
		logrus.Println("No backups created yet for this service.")
	} else if len(*jobs) == 0 {
		logrus.Println("No backups found with the given parameters.")
	}
	return nil
}
开发者ID:catalyzeio,项目名称:cli,代码行数:26,代码来源:list.go


示例10: CmdUpdate

func CmdUpdate(iu IUpdate) error {
	logrus.Println("Checking for available updates...")
	needsUpdate, err := iu.Check()
	if err != nil {
		return err
	}
	// check if we can overwrite exe
	if needsUpdate && (runtime.GOOS == "linux" || runtime.GOOS == "darwin") {
		err = verifyExeDirWriteable()
		if err != nil {
			return err
		}
	}
	if !needsUpdate {
		logrus.Println("You are already running the latest version of the Catalyze CLI")
		return nil
	}
	logrus.Printf("Version %s is available. Updating your CLI...", updater.AutoUpdater.Info.Version)
	err = iu.Update()
	if err != nil {
		return err
	}
	iu.UpdatePods()
	logrus.Printf("Your CLI has been updated to version %s", updater.AutoUpdater.Info.Version)
	return nil
}
开发者ID:catalyzeio,项目名称:cli,代码行数:26,代码来源:update.go


示例11: StartVotingRound

func (sn *Node) StartVotingRound(v *Vote) error {
	log.Println(sn.Name(), "start voting round")
	sn.nRounds = sn.LastSeenRound

	// during view changes, only accept view change related votes
	if sn.ChangingView && v.Vcv == nil {
		log.Println(sn.Name(), "start signing round: changingViewError")
		return ChangingViewError
	}

	sn.nRounds++
	v.Round = sn.nRounds
	v.Index = int(atomic.LoadInt64(&sn.LastSeenVote)) + 1
	v.Count = &Count{}
	v.Confirmed = false
	// only default fill-in view numbers when not prefilled
	if v.View == 0 {
		v.View = sn.ViewNo
	}
	if v.Av != nil && v.Av.View == 0 {
		v.Av.View = sn.ViewNo + 1
	}
	if v.Rv != nil && v.Rv.View == 0 {
		v.Rv.View = sn.ViewNo + 1
	}
	if v.Vcv != nil && v.Vcv.View == 0 {
		v.Vcv.View = sn.ViewNo + 1
	}
	return sn.StartAnnouncement(
		&AnnouncementMessage{LogTest: []byte("vote round"), Round: sn.nRounds, Vote: v})
}
开发者ID:ineiti,项目名称:prifi,代码行数:31,代码来源:signingNode.go


示例12: prepareQuery

func prepareQuery(topic *string, startTime *string, endTime *string, lastEvaluatedKey *map[string]*dynamodb.AttributeValue) *dynamodb.QueryInput {

	params := &dynamodb.QueryInput{
		TableName:         aws.String("midmessages"), // Required
		ConsistentRead:    aws.Bool(false),
		ExclusiveStartKey: prepareLastKey(lastEvaluatedKey),
		ExpressionAttributeNames: map[string]*string{
			"#ts": aws.String("timestamp"),
		},
		ExpressionAttributeValues: *prepareAttrValues(topic, startTime, endTime),
		//FilterExpression:       nil,
		//IndexName:              nil,
		KeyConditionExpression: prepareKeyCondition(topic, startTime, endTime),
		//KeyConditions: nil,
		//		Limit:                aws.Long(1),
		ProjectionExpression: aws.String("topic,#ts,sender,messageID,message,subject,notificationID"),
		//QueryFilter: nil,
		//		ReturnConsumedCapacity: aws.String("TOTAL"),
		ScanIndexForward: aws.Bool(true),
	}

	log.Println("endTime: ", *endTime)

	log.Println("prepareQuery:KeyConditionExpression: ", *params.KeyConditionExpression)

	return params
}
开发者ID:nbcnews,项目名称:midapi,代码行数:27,代码来源:Playback.go


示例13: Wait

func (e *AbstractExecutor) Wait() error {
	e.Build.BuildState = common.Running

	buildTimeout := e.Build.Timeout
	if buildTimeout <= 0 {
		buildTimeout = common.DefaultTimeout
	}

	// Wait for signals: cancel, timeout, abort or finish
	log.Debugln(e.Config.ShortDescription(), e.Build.ID, "Waiting for signals...")
	select {
	case <-e.BuildCanceled:
		log.Println(e.Config.ShortDescription(), e.Build.ID, "Build got canceled.")
		e.Build.FinishBuild(common.Failed, "Build got canceled")

	case <-time.After(time.Duration(buildTimeout) * time.Second):
		log.Println(e.Config.ShortDescription(), e.Build.ID, "Build timedout.")
		e.Build.FinishBuild(common.Failed, "CI Timeout. Execution took longer then %d seconds", buildTimeout)

	case signal := <-e.Build.BuildAbort:
		log.Println(e.Config.ShortDescription(), e.Build.ID, "Build got aborted", signal)
		e.Build.FinishBuild(common.Failed, "Build got aborted: %v", signal)

	case err := <-e.BuildFinish:
		if err != nil {
			return err
		}

		log.Println(e.Config.ShortDescription(), e.Build.ID, "Build succeeded.")
		e.Build.FinishBuild(common.Success, "Build succeeded.")
	}
	return nil
}
开发者ID:AdrianoJS,项目名称:gitlab-ci-multi-runner,代码行数:33,代码来源:executor_abstract.go


示例14: Start

func (c *consulCoordinator) Start(addr net.Addr, errCh chan error) error {
	if addr == nil {
		addr = &net.TCPAddr{}
	}
	c.addr = addr
	session := c.client.Session()
	// set session to delete our keys on invalidation
	sessionOptions := &api.SessionEntry{
		Behavior:  api.SessionBehaviorDelete,
		LockDelay: c.config.LockDelay,
		TTL:       c.config.TTL,
	}
	var sessionID string
	var err error
	err = backoff.RetryNotify(func() error {
		sessionID, _, err = session.Create(sessionOptions, nil)
		return err
	}, backoff.NewExponentialBackOff(), func(err error, t time.Duration) {
		log.Println("Cannot create session, retrying in", t, ". Error:", err)
	})
	if err != nil {
		return fmt.Errorf("failed to create consul session: %v", err)
	}

	// set up a long-running goroutine for renewing the session
	c.sessionRenew = make(chan struct{})
	c.sessionID = sessionID
	log.Println("[coordinator] Coordinator ready")

	go func() {
		errCh <- session.RenewPeriodic("5s", sessionID, nil, c.sessionRenew)
	}()
	return nil
}
开发者ID:nsaje,项目名称:dagger,代码行数:34,代码来源:consul.go


示例15: write

func write(wr writeRequest, id string) {
	cmds, idArr, bufTypeArr := createCommands(wr, id)

	qr := qReport{
		Cmd: "Queued",
		//Type: bufTypeArr,
		Ids:  idArr,
		D:    cmds,
		QCnt: wr.p.itemsInBuffer,
		Port: wr.p.portConf.Name,
	}
	json, _ := json.Marshal(qr)
	h.broadcastSys <- json

	// now send off the commands to the appropriate channel
	for index, cmdToSendToChannel := range cmds {
		//cmdIdCtr++
		//cmdId := "fakeid-" + strconv.Itoa(cmdIdCtr)
		cmdId := idArr[index]
		if bufTypeArr[index] == "Buf" {
			log.Println("Send was normal send, so sending to wr.p.sendBuffered")
			wr.p.sendBuffered <- Cmd{cmdToSendToChannel, cmdId, false, false}
		} else {
			log.Println("Send was sendnobuf, so sending to wr.p.sendNoBuf")
			wr.p.sendNoBuf <- Cmd{cmdToSendToChannel, cmdId, true, false}
		}
	}

	// garbage collect
	if *gcType == "max" {
		debug.FreeOSMemory()
	}

}
开发者ID:brunodisilva,项目名称:arduino-create-agent,代码行数:34,代码来源:serial.go


示例16: DetachVolume

func (d *driver) DetachVolume(
	runAsync bool,
	volumeID, blank string, force bool) error {

	if volumeID == "" {
		return errors.ErrMissingVolumeID
	}

	volumes, err := d.getVolume(volumeID, "")
	if err != nil {
		return err
	}

	if volumes[0].Status == "available" {
		return nil
	}

	_, err = d.ec2Instance.DetachVolume(volumeID, force)
	if err != nil {
		return err
	}

	if !runAsync {
		log.Println("Waiting for volume detachment to complete")
		err = d.waitVolumeDetach(volumeID)
		if err != nil {
			return err
		}
	}

	log.Println("Detached volume", volumeID)
	return nil
}
开发者ID:lucmichalski,项目名称:rexray,代码行数:33,代码来源:ec2.go


示例17: GetGodos

func GetGodos() []model.Godo {
	var godos []model.Godo

	// Load all godos from the database
	rows, err := db.Query("SELECT ID, Title, Content FROM godo ORDER BY Rank")
	if err != nil {
		log.Println(err)
	}

	// Ensure that the database connection is closed
	defer rows.Close()

	for rows.Next() {
		var id int
		var title string
		var content string

		// Fill variables with data from row
		if err := rows.Scan(&id, &title, &content); err != nil {
			log.Println(err)
		}

		// Create a Godo from the extracted data
		godo := model.Godo{
			ID:          id,
			Title:       title,
			ContentMD:   content,
			ContentHTML: template.HTML(string(md.MarkdownCommon([]byte(content))))}

		godos = append(godos, godo)
	}
	return godos
}
开发者ID:ChristianAE,项目名称:GoDo,代码行数:33,代码来源:storage.go


示例18: PopulateTemplates

func PopulateTemplates() {
	templateDir := "./templates/"

	// Get all files in the templates folder
	files, err := ioutil.ReadDir(templateDir)
	if err != nil {
		log.Println("Error population templates")
	}

	var templateFiles []string
	// Iterate over all files to filter for .html
	for _, file := range files {
		filename := file.Name()
		if strings.HasSuffix(filename, ".html") {
			templateFiles = append(templateFiles, templateDir+filename)
		}
	}

	templates, err := template.ParseFiles(templateFiles...)
	if err != nil {
		log.Println("Error population templates")
	}

	templateIndex = templates.Lookup("index.html")
}
开发者ID:ChristianAE,项目名称:GoDo,代码行数:25,代码来源:view.go


示例19: main

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Parse()

	if *profile != "" {
		flag, err := os.Create(*profile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(flag)
		defer pprof.StopCPUProfile()
	}

	if *authTokenFlag == "" {
		*authTokenFlag = "public"
		log.Println("Using default Token", *authTokenFlag)
	}

	if *certFile == "" || *keyFile == "" {
		log.Error("need cert file and key file .pem")
		return
	}
	th := throttled.RateLimit(throttled.PerMin(30),
		&throttled.VaryBy{RemoteAddr: true},
		store.NewMemStore(100),
	)
	mux := http.NewServeMux()
	mux.Handle("/remoton/", http.StripPrefix("/remoton",
		remoton.NewServer(func(authToken string, r *http.Request) bool {
			return authToken == *authTokenFlag
		}, func() string {
			return uuid.NewV4().String()[0:8]
		})))

	log.Println("Listen at HTTPS ", *listenAddr)
	sSecure := &http.Server{
		Addr:    *listenAddr,
		Handler: th.Throttle(mux),
	}
	host, port, err := net.SplitHostPort(*listenAddr)
	if err != nil {
		log.Fatal(err)
	}
	iport, err := strconv.Atoi(port)
	if err != nil {
		panic(err)
	}

	listenInsecureAddr := net.JoinHostPort(host, strconv.Itoa(iport-1))
	//Default insecure it's a previous port
	log.Println("Listen at HTTP ", listenInsecureAddr)
	sInsecure := &http.Server{
		Addr:    listenInsecureAddr,
		Handler: th.Throttle(mux),
	}
	go sInsecure.ListenAndServe()

	log.Fatal(sSecure.ListenAndServeTLS(*certFile, *keyFile))
}
开发者ID:bit4bit,项目名称:remoton,代码行数:60,代码来源:main.go


示例20: findLocationByCoordinates

func findLocationByCoordinates(loc string) *Location {
	p, err := parseCoordinate(loc)
	if err != nil {
		log.Println(err)
		return nil
	}

	addr, err := geocoder.ReverseGeocode(p)
	if err != nil {
		log.Println(err)
		return nil
	}

	tokens := strings.Split(addr, ",")
	country := strings.ToLower(tokens[len(tokens)-1])
	if l, ok := countryTrie.Find(country).(*Location); ok && l != nil {
		l.Address = addr
		return l
	}

	if l := countryCodes[country]; l != nil {
		l.Address = addr
		return l
	}
	return nil
}
开发者ID:rendon,项目名称:loc,代码行数:26,代码来源:api.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang logrus.SetFormatter函数代码示例发布时间:2022-05-28
下一篇:
Golang logrus.Printf函数代码示例发布时间: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