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

Golang v2.Error函数代码示例

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

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



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

示例1: main

func main() {
	db, err := mgo.Dial(os.Getenv("MONGO_URL"))
	if err != nil {
		log.Error("Failed to connect to MongoDB", "error", err)
		os.Exit(1)
		return
	}
	defer db.Close()

	ops, errs := gtm.Tail(db, &gtm.Options{
		OpLogCollectionName: &OplogCollection,
		Filter: func(op *gtm.Op) bool {
			return op.Namespace == "dg.lists"
		},
	})

	for {
		select {
		case err = <-errs:
			log.Error("Error from oplog tail", "error", err)
		case <-ops:
			log.Info("Change event")
			Reload()
		}
	}
}
开发者ID:Ulexus,项目名称:dg-watch,代码行数:26,代码来源:main.go


示例2: main

func main() {

	log.Debug("Starting up...")

	dev, err := i2c.New(0x77, 1)
	if err != nil {
		log.Error("Error: %v", err)
	}
	bme, err := bme280.NewI2CDriver(dev)
	if err != nil {
		log.Error("Error: %v", err)
	}

	for {
		weather, err := bme.Readenv()

		density := atmosphere.AirDensity(atmosphere.TemperatureC(weather.Temp),
			atmosphere.Pressure(weather.Press*100),
			atmosphere.RelativeHumidity(weather.Hum))
		if err != nil {
			log.Error("Error: %v", err)
		} else {
			log.Debug(fmt.Sprintf("Temperature (degC) %2.2f, pressure (mbar) %4.2f, humidity %2.2f, Density %2.3f kg/m3, CorrFact %1.4f",
				weather.Temp, weather.Press, weather.Hum, float64(density), float64(density*0.8)))
		}

		<-time.After(5 * time.Second)
	}
}
开发者ID:dhague,项目名称:aeropi,代码行数:29,代码来源:aeropi.go


示例3: uploadPodcast

func uploadPodcast(r *http.Request) (uploadFile UploadFile, err error) {
	file, header, err := r.FormFile("file")
	if err != nil {
		return uploadFile, err
	}
	defer file.Close()

	target := filepath.Join(common.Storage, header.Filename)
	out, err := os.Create(target)
	if err != nil {
		return uploadFile, err
	}
	defer out.Close()

	// write the content from POST to the file
	_, err = io.Copy(out, file)
	if err != nil {
		return uploadFile, err
	}

	filetype, invalid := isLegalFileFormat(target)
	if invalid {
		log.Error("invalid filetype detected", "file", target, "filetype", filetype)
		deleteError := os.Remove(target)
		if deleteError != nil {
			log.Error("could not delete invalid file", "file", target, "filetype", filetype)
		}
	}

	fileInfo, _ := out.Stat()
	uploadFile.Name = header.Filename
	uploadFile.Size = fileInfo.Size()
	return uploadFile, nil
}
开发者ID:rogierlommers,项目名称:poddy,代码行数:34,代码来源:file.go


示例4: main

func main() {

	app := cli.NewApp()
	app.Name = "Cabify Store"
	app.Usage = "Cabify"
	app.Version = "0.0.1"

	app.Flags = []cli.Flag{
		cli.StringFlag{"config, c", "config.yaml", "config file to use", "APP_CONFIG"},
	}

	app.Commands = []cli.Command{
		{
			Name:  "server",
			Usage: "Run Cabify Store http server",
			Action: func(c *cli.Context) {
				cfg, err := getConfig(c)
				if err != nil {
					log.Error(err.Error())
					return
				}

				svc := service.CabifyService{}

				if err = svc.Run(cfg); err != nil {
					log.Error(err.Error())
				}

				log.Info("Cabify Store server started")
			},
		},
	}
	app.Run(os.Args)
}
开发者ID:AntonMaltsev,项目名称:cabstore,代码行数:34,代码来源:server.go


示例5: moveMP3toStorageDirectory

func moveMP3toStorageDirectory(watchdir, storage string) {
	files, err := ioutil.ReadDir(watchdir)
	if err != nil {
		log.Error("scan error", "error", err)
		return
	}

	for _, file := range files {
		if !file.IsDir() {
			if strings.HasSuffix(file.Name(), "mp3") {
				source := filepath.Join(watchdir, file.Name())
				target := filepath.Join(storage, file.Name())

				// first copy file
				log.Info("about to copy file", "source", source, "target", target)
				err := copyFileContents(source, target)
				if err != nil {
					log.Error("copy error", "error", err)
					return
				}

				// then delete original file
				err = os.Remove(source)
				if err != nil {
					log.Error("error deleting source file", "error", err)
				}
			}
			log.Debug("only process mp3 files")
		}
	}
}
开发者ID:rogierlommers,项目名称:poddy,代码行数:31,代码来源:file.go


示例6: Write

// Write out the new files
func Write() error {
	var err error
	var result Item

	// Create the temp files
	wl, err := os.Create("/etc/dansguardian/exceptionlist_db")
	if err != nil {
		log.Error("Failed to create temporary whitelist", "error", err)
		return err
	}
	defer wl.Close()

	gl, err := os.Create("/etc/dansguardian/greylist_db")
	if err != nil {
		log.Error("Failed to create temporary greylist", "error", err)
		return err
	}
	defer gl.Close()

	bl, err := os.Create("/etc/dansguardian/blacklist_db")
	if err != nil {
		log.Error("Failed to create temporary blacklist", "error", err)
		return err
	}
	defer bl.Close()

	// Get the list
	session, err := mgo.Dial(os.Getenv("MONGO_URL"))
	if err != nil {
		log.Error("Failed to connect to MongoDB", "error", err)
		return err
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	i := session.DB("dg").C("lists").Find(nil).Iter()
	for i.Next(&result) {
		switch result.List {
		case "whitelist":
			_, err = wl.WriteString(fmt.Sprintf("%s\n", result.Name))
		case "greylist":
			_, err = gl.WriteString(fmt.Sprintf("%s\n", result.Name))
		case "blacklist":
			_, err = bl.WriteString(fmt.Sprintf("%s\n", result.Name))
		}
	}

	return err
}
开发者ID:Ulexus,项目名称:dg-watch,代码行数:49,代码来源:main.go


示例7: TestAudioToBracelet

func TestAudioToBracelet(t *testing.T) {
	llog.Info("Start test")
	audio, err := s.GetAudio("./test.amr")
	if err != nil {
		llog.Error("Erorr", "err", err)
		t.FailNow()
	}

	length := len(audio)
	// Divide file in parts
	var parts int
	if length%s.BufferSize == 0 {
		parts = length / s.BufferSize
	} else {
		parts = length/s.BufferSize + 1
	}

	from := Expect{"ARA": Data{"", 1, "666"}, "ASA": Data{"", 1, "666"}, "ARD": Data{"", 1, ""}}
	to := Expect{"RAU": Data{"", 1, ""}, "SAE": Data{"", 1, ""}} // "SAU": Data{"", parts, ""},

	br := Registration(from, to, t)
	br.Lock()
	br.Commands["666"] = audio
	br.Unlock()

	command := fmt.Sprintf("RAU&M%v&%v&%v&%v&%v&%v", br.Clients[0], 666, length, parts, 10, "DF")
	br, from, to = SendInstruction(br, from, to, command, "ARD", false, t)

	if !(from.Done() && to.Done()) {
		t.Fail()
	}
	br.Logger.Info("End of the test")
	server.RemoveBracelet(TestingID)
	llog.Info("End test")
}
开发者ID:seka17,项目名称:bracelet,代码行数:35,代码来源:bracelet_test.go


示例8: SendInstruction

func SendInstruction(br *s.Bracelet, from, to Expect, command string, header string, check bool, t *testing.T) (*s.Bracelet, Expect, Expect) {
	if command != "" {
		if _, err := br.Write(command); err != nil {
			llog.Error("Err", "error", err)
			t.Fatal("Can't write message to bracelet")
		}
		br.Logger.Info("Execute", "command", command)
		to.Check(command, "to bracelet")
	}
	ch := make(chan struct{}, 200)
	for i := 0; i < 200; i++ {
		ch <- struct{}{}
	}
	go Listen(br, from, to, t, ch)
	for {
		if header == "" {
			time.Sleep(time.Second * 5)
			break
		}
		if from[header].Msg == "" {
			time.Sleep(time.Second * 5)
			continue
		}
		if !from.CheckStatus(header) && check {
			t.Fatal("Wrong code")
		}
		break
	}
	Wait()
	close(ch)
	return br, from, to
}
开发者ID:seka17,项目名称:bracelet,代码行数:32,代码来源:bracelet_test.go


示例9: main

func main() {
	// read environment vars
	common.ReadEnvironment()

	// initialise mux router
	router := mux.NewRouter()

	// setup statics
	poddy.CreateStaticBox(router)

	// setup watchdirectory
	if common.Watch != "" {
		check, err := os.Stat(common.Watch)
		if err != nil || !check.IsDir() {
			log.Error("error setting up watchdirectory (point to directory?)")
		} else {
			poddy.EnableWatchdirectory(common.Watch)
		}
	}

	// http handles
	router.HandleFunc("/", poddy.IndexPage)
	router.HandleFunc("/add-podcast", poddy.AddPodcast)
	router.HandleFunc("/feed", poddy.Feed)
	router.PathPrefix("/download").Handler(http.StripPrefix("/download", http.FileServer(http.Dir("storage/"))))

	// start server
	log.Info("poddy is running/listening", "host", common.Host, "port", common.Port)
	err := http.ListenAndServe(fmt.Sprintf("%s:%d", common.Host, common.Port), router)
	if err != nil {
		log.Crit("daemon could not bind on interface", "host", common.Host, "port", common.Port)
		os.Exit(1)
	}
}
开发者ID:rogierlommers,项目名称:poddy,代码行数:34,代码来源:main.go


示例10: getData

// GetData retrieves and calculates the metrics to be displayed in the report page.
func getData(data *Info) error {
	currentFolder, err := osext.ExecutableFolder()
	if err != nil {
		log.Error("Could not retrieve current folder. Attempting to use dot(.) instead...", "error", err)
		currentFolder = "."
	}

	dbFilePath := currentFolder + "/values.db"
	db, err := sql.Open("sqlite3", dbFilePath)
	if err != nil {
		log.Crit("Failed to opend database", "error", err, "path", dbFilePath)
		return err
	}
	defer db.Close()

	rows, err := db.Query("SELECT timestamp, ping, download, upload FROM bandwidth")
	if err != nil {
		log.Crit("Could not retrieve data from database", "error", err)
		return err
	}
	defer rows.Close()

	min := 10000.0 // Unfortunately, I don't see myself with a 10000Mbit/s connection anytime soon...
	max := 0.0
	counter := 0
	average := 0.0
	data.Points = [][]interface{}{{map[string]string{"type": "datetime", "label": "Time"}, "Download", "Upload"}}

	for rows.Next() {
		var timestamp string
		var ping, download, upload float64
		rows.Scan(&timestamp, &ping, &download, &upload)

		if download < min {
			min = download
		}

		if download > max {
			max = download
		}

		average += download
		counter++

		// Timestamp is presented as YYYY-MM-DD HH:MI:SS.Milli+0000
		split := strings.Split(timestamp, " ")
		dateOnly := strings.Split(string(split[0]), "-")
		timeOnly := strings.Split(string(split[1]), ".")
		timeOnly = strings.Split(string(timeOnly[0]), ":")
		axis := fmt.Sprintf("Date(%s, %s, %s, %s, %s, %s)", dateOnly[0], dateOnly[1], dateOnly[2], timeOnly[0], timeOnly[1], timeOnly[2])

		data.Points = append(data.Points, []interface{}{axis, download, upload})
	}
	data.MinValue = min
	data.MaxValue = max
	data.AvgValue = average / float64(counter)
	data.LastValue = data.Points[len(data.Points)-1][1].(float64)

	return nil
}
开发者ID:otaviokr,项目名称:check-my-speed,代码行数:61,代码来源:handlers.go


示例11: Reload

// Reload Dansguardian configurations
func Reload() {
	err := Write()
	if err != nil {
		log.Error("Failed to write new files; not reloading Dansguardian", "error", err)
		return
	}

	// Tell dansguardian to reload
	cmd := exec.Command("/usr/sbin/dansguardian", "-g")
	err = cmd.Run()
	if err != nil {
		log.Error("Failed to reload dansguardian", "error", err)
	}

	return
}
开发者ID:Ulexus,项目名称:dg-watch,代码行数:17,代码来源:main.go


示例12: startDownloader

func (a *albumJob) startDownloader() {
	defer a.downloadSync.Done()

	for item := range a.downloadQueue {
		buf := a.bufferPool.Get()

		log.Debug("Processing album item",
			"artist", item.Artist,
			"title", item.Title,
			"url", item.ItemURL,
		)

		err := downloadURL(buf, item.DownloadURL)
		if err != nil {
			log.Error("Unable to download item",
				"download_url", item.DownloadURL,
				"error", err,
			)
			return
		}
		a.zipQueue <- zipFile{
			Filename: item.Name(),
			Buffer:   buf,
		}
		log.Info("Processed album item",
			"download_url", item.DownloadURL,
			"filename", item.Name(),
		)
	}
}
开发者ID:Taik,项目名称:zing-mp3,代码行数:30,代码来源:main.go


示例13: handleTCPRequest

func (p *Peer) handleTCPRequest(conn net.Conn) {
	defer conn.Close()

	b := make([]byte, 1024)
	reader := bufio.NewReader(conn)
	_, err := reader.Read(b)

	if err != nil {
		log.Error("Read error", log.Ctx{"error": err})
		return
	}

	// decode
	r, err := decode(b, p.config.EncryptionKey)

	if err != nil {
		p.logger.Error("Decode error", log.Ctx{"error": err})
		return
	}

	switch r.(type) {
	case *joinRequest:

		p.store.peerAdd(r.(*joinRequest).Peer)

		joinResponse := &joinResponse{
			Peer:  p.store.toPeer(),
			Peers: p.store.toMap(),
		}

		r, err := encode(joinResponse, p.config.EncryptionKey, p.config.UDPBufferSize)
		if err != nil {
			p.logger.Error("Encode error", log.Ctx{"error": err})
			return
		}

		_, err = conn.Write(r)
		if err != nil {
			p.logger.Error("Write error", log.Ctx{"error": err})
		}

		return
	default:
		log.Error("Unknown type")
	}

}
开发者ID:sisatech,项目名称:cluster,代码行数:47,代码来源:handle.go


示例14: fatalErr

// This function logs a fatal error and kills the process.
func fatalErr(err error, prefix string) {
	if err != nil {
		defer db.Close()
		msg := fmt.Sprintf("%s: %s", prefix, err.Error())
		log.Error(msg)
		panic(msg)
	}
}
开发者ID:bradberger,项目名称:mqtt-client-logger,代码行数:9,代码来源:errors.go


示例15: loadConfig

func loadConfig(c *Config) {
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		log.Error("Fatal error config file.", "error", err)
	} else {
		c.Alert = viper.Get("alert")
	}

}
开发者ID:bradobro,项目名称:corazones,代码行数:9,代码来源:config.go


示例16: main

func main() {
	options := cfg.GetOptions()

	log.Info("Server is ready!", "port", options.Port, "token", options.Token)
	log.Info(fmt.Sprintf("Listening for post requests on http://localhost:%s/events", options.Port))
	log.Info(fmt.Sprintf("SSE streaming avaliable on http://localhost:%s/stream", options.Port))

	es := eventsource.New(
		eventsource.DefaultSettings(),
		func(req *http.Request) [][]byte {
			return [][]byte{
				[]byte("X-Accel-Buffering: no"),
				[]byte("Access-Control-Allow-Origin: *"),
				[]byte("Cache-Control: no-cache"),
			}
		},
	)

	defer es.Close()

	r := mux.NewRouter()

	r.Handle("/stream", es)

	r.HandleFunc("/event/{event}/{id}", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			if token, ok := r.Header["X-Token"]; ok {
				if token[0] == options.Token {
					event := mux.Vars(r)["event"]
					id := mux.Vars(r)["id"]

					data, err := ioutil.ReadAll(r.Body)
					if err != nil {
						log.Error("Cannot read body", "err", err)
					}

					es.SendEventMessage(string(data), event, id)
					log.Info("Message has been sent", "id", id, "event", event)

				} else {
					log.Warn("The request has wrong token", "token", token[0])
					http.Error(w, "The request has wrong token", http.StatusUnauthorized)
				}
			} else {
				log.Warn("The request doesn't contain authentication token")
				http.Error(w, "The request doesn't contain authentication token", http.StatusUnauthorized)
			}
		} else {
			log.Warn("Received wrong http request")
			http.Error(w, "POST requests only", http.StatusMethodNotAllowed)
		}
	})

	r.Handle("/", http.FileServer(http.Dir("./public")))
	http.ListenAndServe(fmt.Sprintf(":%s", options.Port), r)
}
开发者ID:mrded,项目名称:goPusher,代码行数:56,代码来源:main.go


示例17: init

func init() {
	cfg, err := ini.Load("./config.ini")

	if err != nil {
		log.Error("Cannot read ./config.ini;", "err", err)
	}

	options.Port = cfg.Section("").Key("port").String()
	options.Token = cfg.Section("").Key("token").String()
}
开发者ID:mrded,项目名称:goPusher,代码行数:10,代码来源:cfg.go


示例18: genSessionID

func genSessionID() ([]byte, error) {
	sessionID := make([]byte, 16)
	_, err := io.ReadFull(rand.Reader, sessionID)
	if err != nil {
		log.Error("Unable to create session because unable to read random bytes", "error", err)
		return nil, err
	}

	return sessionID, err
}
开发者ID:jackc,项目名称:tpr,代码行数:10,代码来源:domain.go


示例19: downloadURL

func downloadURL(buf *bytes.Buffer, url string) error {
	log.Debug("Downloading item", "download_url", url)
	response, err := http.Get(url)
	if err != nil {
		log.Error("Unable to request album item", "download_url", url)
		return err
	}
	defer response.Body.Close()
	io.Copy(buf, response.Body)

	return nil
}
开发者ID:Taik,项目名称:zing-mp3,代码行数:12,代码来源:main.go


示例20: loadUsersCSV

func loadUsersCSV() error {
	// Open and parse existing users from the uat file
	usersFile, err := os.OpenFile("users.csv", os.O_RDWR|os.O_CREATE, 0664)
	if err != nil {
		log.Error("Failed to open users file", "error", err.Error())
		return err
	}
	defer usersFile.Close()

	csvReader := csv.NewReader(usersFile)
	rawCSV, err := csvReader.ReadAll()
	if err != nil {
		log.Error("Failed to read CSV file", "error", err.Error())
		return err
	}

	for _, row := range rawCSV {
		u := User{row[0], row[1]}
		Users[u.Username] = u
	}

	return nil
}
开发者ID:begizi,项目名称:helios-server,代码行数:23,代码来源:github.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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