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

Golang expvar.NewString函数代码示例

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

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



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

示例1: New

func New(inst string) {
	instance = inst

	exp.Exp(metrics.DefaultRegistry)

	expvar.NewString("instance").Set(instance)
	expvar.NewString("service").Set(service)
}
开发者ID:graphite-ng,项目名称:carbon-relay-ng,代码行数:8,代码来源:metrics_wrapper.go


示例2: init

func init() {
	expvar.NewString("goVersion").Set(runtime.Version())
	expvar.NewString("iconVersion").Set(besticon.VersionString)

	expvar.NewString("timeLastDeploy").Set(parseUnixTimeStamp(os.Getenv("DEPLOYED_AT")).String())
	expvar.NewString("timeStartup").Set(time.Now().String())
	expvar.Publish("timeCurrent", expvar.Func(func() interface{} { return time.Now() }))
}
开发者ID:undernewmanagement,项目名称:besticon,代码行数:8,代码来源:expvar.go


示例3: main

func main() {

	port := flag.Int("p", 8080, "port to listen on")
	input := flag.String("f", "", "file with signatures to load")
	useVPTree := flag.Bool("vptree", true, "load vptree")
	useStore := flag.Bool("store", true, "load simstore")
	storeSize := flag.Int("size", 6, "simstore size (3/6)")
	cpus := flag.Int("cpus", runtime.NumCPU(), "value of GOMAXPROCS")
	myNumber := flag.Int("no", 0, "id of this machine")
	totalMachines := flag.Int("of", 1, "number of machines to distribute the table among")
	small := flag.Bool("small", false, "use small memory for size 3")

	flag.Parse()

	expvar.NewString("BuildVersion").Set(BuildVersion)

	log.Println("starting simd", BuildVersion)

	log.Println("setting GOMAXPROCS=", *cpus)
	runtime.GOMAXPROCS(*cpus)

	if *input == "" {
		log.Fatalln("no import hash list provided (-f)")
	}

	err := loadConfig(*input, *useStore, *storeSize, *small, *useVPTree, *myNumber, *totalMachines)
	if err != nil {
		log.Fatalln("unable to load config:", err)
	}

	if *useStore {
		http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) { searchHandler(w, r) })
	}

	if *useVPTree {
		http.HandleFunc("/topk", func(w http.ResponseWriter, r *http.Request) { topkHandler(w, r) })
	}

	go func() {
		sigs := make(chan os.Signal)
		signal.Notify(sigs, syscall.SIGHUP)

		for {
			select {
			case <-sigs:
				log.Println("caught SIGHUP, reloading")

				err := loadConfig(*input, *useStore, *storeSize, *small, *useVPTree, *myNumber, *totalMachines)
				if err != nil {
					log.Println("reload failed: ignoring:", err)
					break
				}
			}
		}

	}()

	log.Println("listening on port", *port)
	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*port), nil))
}
开发者ID:xukai504087493,项目名称:go-simstore,代码行数:60,代码来源:main.go


示例4: main

func main() {
	flag.Parse()
	expvar.NewString("listen_port").Set(*listenPort)

	stdout := log.New(os.Stdout, "", log.Ldate|log.Ltime)
	stderr := log.New(os.Stderr, "", log.Ldate|log.Ltime)

	http.Handle("/msg", idHandler(stdout, stderr))

	logMessage(stdout,
		&Message{
			Source: &PROG,
			Key:    &STATUS,
			Content: map[string]interface{}{
				"status": "listening",
				"port":   *listenPort,
			},
		})

	err := http.ListenAndServe(fmt.Sprintf(":%s", *listenPort), nil)
	if err != nil {
		logMessage(stderr,
			&Message{
				Source: &PROG,
				Key:    &ERR,
				Content: map[string]interface{}{
					"error": fmt.Sprintf("error starting to listen: %s", err),
				},
			})
		os.Exit(1)
	}
}
开发者ID:JoelPM,项目名称:httpjsonlogger,代码行数:32,代码来源:httpjsonlogger.go


示例5: init

func init() {
	expvar.NewString("service.startTime").Set(time.Now().String())

	// Suppress usage output. Any errors will be complained about when the user
	// parses flags anyway.
	fs.Usage = func() {}
	fs.SetOutput(nullWriter{})
}
开发者ID:postfix,项目名称:service,代码行数:8,代码来源:service.go


示例6: init

func init() {
	currentTar = expvar.NewString("CurrentTar")
	tarBytesRead = expvar.NewInt("TarBytesRead")
	tarsFailed = expvar.NewInt("TarsFailed")
	tarsIndexed = expvar.NewInt("TarsIndexed")
	tarsSkipped = expvar.NewInt("TarsSkipped")
	tracesFailed = expvar.NewInt("TracesFailed")
	tracesIndexed = expvar.NewInt("TracesIndexed")
}
开发者ID:sburnett,项目名称:bismark-passive-server-go,代码行数:9,代码来源:index.go


示例7: NewMetrics

//NewMetrics creates
//Metrics object
func NewMetrics() *Metrics {
	metrics = &Metrics{
		true,
		expvar.NewInt("comparisons"),
		expvar.NewInt("errors"),
		expvar.NewString("database"),
	}
	return metrics
}
开发者ID:sohlich,项目名称:go-plag,代码行数:11,代码来源:metrics.go


示例8: init

func init() {
	expvar.NewInt("NumCPUs").Set(int64(runtime.NumCPU()))

	revision, err := exec.Command("git", "log", "-1", "--pretty=oneline", "HEAD").Output()
	if err != nil {
		expvar.NewString("revision").Set(fmt.Sprintf("Could not determine git version: %s", err))
	} else {
		expvar.NewString("revision").Set(strings.TrimSpace(string(revision)))
	}

	env := expvar.NewMap("env")
	for _, val := range os.Environ() {
		parts := strings.SplitN(val, "=", 2)
		if len(parts) >= 2 {
			env.Set(parts[0], exposedString{parts[1]})
		}
	}
}
开发者ID:vinays,项目名称:goodies,代码行数:18,代码来源:expvar.go


示例9: main

func main() {

	Whispers = whispers{metrics: make(map[string]*carbonmem.Whisper)}

	flag.IntVar(&Whispers.windowSize, "w", 600, "window size")
	flag.IntVar(&Whispers.epochSize, "e", 60, "epoch window size")
	flag.IntVar(&Whispers.epoch0, "epoch0", 0, "epoch0")
	flag.IntVar(&Whispers.prefix, "prefix", 0, "prefix nodes to shard on")

	port := flag.Int("p", 8001, "port to listen on (http)")
	gport := flag.Int("gp", 2003, "port to listen on (graphite)")
	verbose := flag.Bool("v", false, "verbose logging")
	logdir := flag.String("logdir", "/var/log/carbonmem/", "logging directory")
	logtostdout := flag.Bool("stdout", false, "log also to stdout")

	flag.Parse()

	rl := rotatelogs.NewRotateLogs(
		*logdir + "/carbonmem.%Y%m%d%H%M.log",
	)

	// Optional fields must be set afterwards
	rl.LinkName = *logdir + "/carbonmem.log"

	if *logtostdout {
		log.SetOutput(io.MultiWriter(os.Stdout, rl))
	} else {
		log.SetOutput(rl)
	}

	expvar.NewString("BuildVersion").Set(BuildVersion)
	log.Println("starting carbonmem", BuildVersion)

	expvar.Publish("Whispers", expvar.Func(func() interface{} {
		m := make(map[string]int)
		Whispers.RLock()
		for k, v := range Whispers.metrics {
			m[k] = v.Len()
		}
		Whispers.RUnlock()
		return m
	}))

	if Whispers.epoch0 == 0 {
		Whispers.epoch0 = int(time.Now().Unix())
	}

	go graphiteServer(*gport)

	http.HandleFunc("/metrics/find/", accessHandler(*verbose, findHandler))
	http.HandleFunc("/render/", accessHandler(*verbose, renderHandler))

	log.Println("http server starting on port", *port)
	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*port), nil))
}
开发者ID:tsheasha,项目名称:carbonmem,代码行数:55,代码来源:main.go


示例10: exportBinaryVersion

func exportBinaryVersion() {
	hasher := md5.New()
	exeFile, err := os.Open("/proc/self/exe")
	if err != nil {
		panic(err)
	}
	if _, err = io.Copy(hasher, exeFile); err != nil {
		panic(err)
	}
	md5sum := hex.EncodeToString(hasher.Sum(nil))
	fileInfo, err := exeFile.Stat()
	if err != nil {
		panic(err)
	}
	mtime := fileInfo.ModTime().Format(time.RFC3339)
	version := mtime + " " + md5sum
	expvar.NewString("binary-version").Set(version)
	// rexport this value for varz scraper
	expvar.NewString("Version").Set(version)
}
开发者ID:seacoastboy,项目名称:vitess,代码行数:20,代码来源:vtocc.go


示例11: NewRuntimeWare

func NewRuntimeWare(prefixes []string, trackPageview bool, logInterval ...time.Duration) Middleware {
	expvar.NewString("at_server_start").Set(time.Now().Format("2006-01-02 15:04:05"))
	expvar.NewInt("cpu_count").Set(int64(runtime.NumCPU()))
	ware := &RuntimeWare{
		serverStarted: time.Now(),
		trackPageview: trackPageview,
		ignoredUrls:   prefixes,
		cQps:          ratecounter.NewRateCounter(time.Minute),
		c4xx:          ratecounter.NewRateCounter(5 * time.Minute),
		c5xx:          ratecounter.NewRateCounter(5 * time.Minute),
		lc:            NewLatencyCounter(50),
		hitsTotal:     expvar.NewInt("hits_total"),
		hitsQps:       expvar.NewInt("hits_per_minute"),
		hits4xx:       expvar.NewInt("hits_4xx_per_5min"),
		hits5xx:       expvar.NewInt("hits_5xx_per_5min"),
		hitsServed:    expvar.NewString("latency_recent"),
		hitsLatMax:    expvar.NewString("latency_max"),
		hitsLatMin:    expvar.NewString("latency_min"),
		hitsLat95:     expvar.NewString("latency_p95"),
		hitsLat50:     expvar.NewString("latency_p50"),
		numGoroutine:  expvar.NewInt("goroutine_count"),
	}
	if trackPageview {
		ware.pageviews = expvar.NewMap("hits_pageviews")
	}
	if len(logInterval) > 0 && logInterval[0] > 0 {
		go ware.logSnapshot(logInterval[0])
	}
	return ware
}
开发者ID:haobaozhong,项目名称:sweb,代码行数:30,代码来源:runtime.go


示例12: init

func init() {
	registry := metrics.NewPrefixedChildRegistry(metrics.DefaultRegistry, "daemon_")
	registry.Register("open_fds", openFDs)
	registry.Register("goroutines", goroutines)
	registry.Register("threads", threads)
	registry.Register("connections", conns)

	registry.Register("hc_openfd", metrics.NewHealthcheck(fdHealthCheck))
	registry.Register("hc_threads", metrics.NewHealthcheck(threadHealthCheck))

	http.Handle("/metrics", exportmetrics.HTTPExport(metrics.DefaultRegistry))

	expvar.NewString("version_info").Set(fmt.Sprintf("version:%s hash:%s build:%s tag:%s",
		version.Version, version.GitHash, version.Build, version.GitTag))
}
开发者ID:noxiouz,项目名称:stout,代码行数:15,代码来源:main.go


示例13: init

func init() {
	currentTar = expvar.NewString("CurrentTar")
	tarBytesRead = expvar.NewInt("TarBytesRead")
	tarsFailed = expvar.NewInt("TarsFailed")
	tarsIndexed = expvar.NewInt("TarsIndexed")
	tarsSkipped = expvar.NewInt("TarsSkipped")
	statsFailed = expvar.NewInt("StatsFailed")
	statsIndexed = expvar.NewInt("StatsIndexed")

	timestampActiveSkipped = expvar.NewInt("TimestampActiveSkipped")
	timestampBismarkExperimentsManagerSkipped = expvar.NewInt("TimestampBismarkExperimentsManagerSkipped")
	timestampBismarkUpdaterSkipped = expvar.NewInt("TimestampBismarkUpdaterSkipped")
	timestampHealthSkipped = expvar.NewInt("TimestampHealthSkipped")
	timestampMacAnalyzerSkipped = expvar.NewInt("TimestampMacAnalyzerSkipped")
	timestampPassiveSkipped = expvar.NewInt("TimestampPassiveSkipped")
	timestampPassiveFrequentSkipped = expvar.NewInt("TimestampPassiveFrequentSkipped")
	timestampOtherSkipped = expvar.NewInt("TimestampOtherSkipped")
}
开发者ID:sburnett,项目名称:bismark-tools,代码行数:18,代码来源:stats.go


示例14: main

func main() {
	var inerInt int64 = 10
	pubInt := expvar.NewInt("Int")
	pubInt.Set(inerInt)
	pubInt.Add(2)

	var inerFloat float64 = 1.2
	pubFloat := expvar.NewFloat("Float")
	pubFloat.Set(inerFloat)
	pubFloat.Add(0.1)

	var inerString string = "hello gophers"
	pubString := expvar.NewString("String")
	pubString.Set(inerString)

	pubMap := expvar.NewMap("Map").Init()
	pubMap.Set("Int", pubInt)
	pubMap.Set("Float", pubFloat)
	pubMap.Set("String", pubString)
	pubMap.Add("Int", 1)
	pubMap.Add("NewInt", 123)
	pubMap.AddFloat("Float", 0.5)
	pubMap.AddFloat("NewFloat", 0.9)
	pubMap.Do(kvfunc)

	expvar.Do(kvfunc)

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "hello gophers")
	})
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		panic(err)
	}

}
开发者ID:JamesJiangCHN,项目名称:gopkg,代码行数:36,代码来源:testExpvar.go


示例15: init

package main

import (
	"expvar"
	"github.com/duego/cryriver/mongodb"
	"log"
	"os"
	"time"
)

var (
	lastEsSeen     *mongodb.Timestamp
	lastEsSeenC    = make(chan *mongodb.Timestamp, 1)
	lastEsSeenStat = expvar.NewString("Last optime seen")
)

func init() {
	// Restore any previously saved timestamp
	lastEsSeen = new(mongodb.Timestamp)
	if f, err := os.Open(*optimeStore); err != nil {
		log.Println("Failed to load previous lastEsSeen timestamp:", err)
	} else {
		lastEsSeen.Load(f)
		f.Close()
	}
	go saveLastEsSeen()
}

// saveLastEsSeen loops the channel to save our progress on what timestamp we have seen so far.
// It will be flushed to disk when our timer ticks.
func saveLastEsSeen() {
开发者ID:ehogberg,项目名称:cryriver,代码行数:31,代码来源:optimestamp.go


示例16: main

func main() {

	z := flag.String("z", "", "zipper")
	port := flag.Int("p", 8080, "port")
	l := flag.Int("l", 20, "concurrency limit")
	cacheType := flag.String("cache", "mem", "cache type to use")
	mc := flag.String("mc", "", "comma separated memcached server list")
	memsize := flag.Int("memsize", 0, "in-memory cache size in MB (0 is unlimited)")
	cpus := flag.Int("cpus", 0, "number of CPUs to use")
	tz := flag.String("tz", "", "timezone,offset to use for dates with no timezone")
	graphiteHost := flag.String("graphite", "", "graphite destination host")
	logdir := flag.String("logdir", "/var/log/carbonapi/", "logging directory")
	logtostdout := flag.Bool("stdout", false, "log also to stdout")
	interval := flag.Duration("i", 60*time.Second, "interval to report internal statistics to graphite")
	idleconns := flag.Int("idleconns", 10, "max idle connections")
	pidFile := flag.String("pid", "", "pidfile (default: empty, don't create pidfile)")

	flag.Parse()

	if *logdir == "" {
		mlog.SetRawStream(os.Stdout)
	} else {
		mlog.SetOutput(*logdir, "carbonapi", *logtostdout)
	}

	expvar.NewString("BuildVersion").Set(BuildVersion)
	logger.Logln("starting carbonapi", BuildVersion)

	if p := os.Getenv("PORT"); p != "" {
		*port, _ = strconv.Atoi(p)
	}

	Limiter = newLimiter(*l)

	if *z == "" {
		logger.Fatalln("no zipper provided")
	}

	if _, err := url.Parse(*z); err != nil {
		logger.Fatalln("unable to parze zipper:", err)
	}

	logger.Logln("using zipper", *z)
	Zipper = zipper{
		z: *z,
		client: &http.Client{
			Transport: &http.Transport{
				MaxIdleConnsPerHost: *idleconns,
			},
		},
	}

	switch *cacheType {
	case "memcache":
		if *mc == "" {
			logger.Fatalln("memcache cache requested but no memcache servers provided")
		}

		servers := strings.Split(*mc, ",")
		logger.Logln("using memcache servers:", servers)
		queryCache = &memcachedCache{client: memcache.New(servers...)}
		findCache = &memcachedCache{client: memcache.New(servers...)}

	case "mem":
		qcache := &expireCache{ec: ecache.New(uint64(*memsize * 1024 * 1024))}
		queryCache = qcache
		go queryCache.(*expireCache).ec.ApproximateCleaner(10 * time.Second)

		findCache = &expireCache{ec: ecache.New(0)}
		go findCache.(*expireCache).ec.ApproximateCleaner(10 * time.Second)

		Metrics.CacheSize = expvar.Func(func() interface{} {
			return qcache.ec.Size()
		})
		expvar.Publish("cache_size", Metrics.CacheSize)

		Metrics.CacheItems = expvar.Func(func() interface{} {
			return qcache.ec.Items()
		})
		expvar.Publish("cache_items", Metrics.CacheItems)

	case "null":
		queryCache = &nullCache{}
		findCache = &nullCache{}
	}

	if *tz != "" {
		fields := strings.Split(*tz, ",")
		if len(fields) != 2 {
			logger.Fatalf("expected two fields for tz,seconds, got %d", len(fields))
		}

		var err error
		offs, err := strconv.Atoi(fields[1])
		if err != nil {
			logger.Fatalf("unable to parse seconds: %s: %s", fields[1], err)
		}

		defaultTimeZone = time.FixedZone(fields[0], offs)
		logger.Logf("using fixed timezone %s, offset %d ", defaultTimeZone.String(), offs)
//.........这里部分代码省略.........
开发者ID:Civil,项目名称:carbonapi,代码行数:101,代码来源:main.go


示例17: init

func init() {
	expvar.NewString("BuildID").Set(BuildID)
	expvar.NewString("BuildTime").Set(BuildTime)
}
开发者ID:rf152,项目名称:boulder,代码行数:4,代码来源:util.go


示例18: init

func init() {
	versionVar := expvar.NewString("dex.version")
	versionVar.Set(version)
}
开发者ID:otsimo,项目名称:accounts,代码行数:4,代码来源:main.go


示例19: main

func main() {
	addr := flag.String("a", ":2003", "address to bind to")
	reportaddr := flag.String("reportaddr", ":8080", "address to bind http report interface to")
	verbose := flag.Bool("v", false, "enable verbose logging")
	debug := flag.Bool("vv", false, "enable more verbose (debug) logging")
	whisperdata := flag.String("w", config.WhisperData, "location where whisper files are stored")
	maxprocs := flag.Int("maxprocs", runtime.NumCPU()*80/100, "GOMAXPROCS")
	logdir := flag.String("logdir", "/var/log/carbonwriter/", "logging directory")
	schemafile := flag.String("schemafile", "/etc/carbon/storage-schemas.conf", "storage-schemas.conf location")
	aggrfile := flag.String("aggrfile", "/etc/carbon/storage-aggregation.conf", "storage-aggregation.conf location")
	logtostdout := flag.Bool("stdout", false, "log also to stdout")

	flag.Parse()

	rl := rotatelogs.NewRotateLogs(
		*logdir + "/carbonwriter.%Y%m%d%H%M.log",
	)

	// Optional fields must be set afterwards
	rl.LinkName = *logdir + "/carbonwriter.log"

	if *logtostdout {
		log.SetOutput(io.MultiWriter(os.Stdout, rl))
	} else {
		log.SetOutput(rl)
	}

	expvar.NewString("BuildVersion").Set(BuildVersion)
	log.Println("starting carbonwriter", BuildVersion)

	loglevel := LOG_NORMAL
	if *verbose {
		loglevel = LOG_DEBUG
	}
	if *debug {
		loglevel = LOG_TRACE
	}

	logger = logLevel(loglevel)

	schemas, err := readStorageSchemas(*schemafile)
	if err != nil {
		logger.Logf("failed to read %s: %s", *schemafile, err.Error())
		os.Exit(1)
	}

	aggrs, err := readStorageAggregations(*aggrfile)
	if err != nil {
		logger.Logf("failed to read %s: %s", *aggrfile, err.Error())
		os.Exit(1)
	}

	config.WhisperData = strings.TrimRight(*whisperdata, "/")
	logger.Logf("writing whisper files to: %s", config.WhisperData)
	logger.Logf("reading storage schemas from: %s", *schemafile)
	logger.Logf("reading aggregation rules from: %s", *aggrfile)

	runtime.GOMAXPROCS(*maxprocs)
	logger.Logf("set GOMAXPROCS=%d", *maxprocs)

	httputil.PublishTrackedConnections("httptrack")
	expvar.Publish("requestBuckets", expvar.Func(renderTimeBuckets))

	// +1 to track every over the number of buckets we track
	timeBuckets = make([]int64, config.Buckets+1)

	// nothing in the config? check the environment
	if config.GraphiteHost == "" {
		if host := os.Getenv("GRAPHITEHOST") + ":" + os.Getenv("GRAPHITEPORT"); host != ":" {
			config.GraphiteHost = host
		}
	}

	// only register g2g if we have a graphite host
	if config.GraphiteHost != "" {

		logger.Logf("Using graphite host %v", config.GraphiteHost)

		// register our metrics with graphite
		graphite, err := g2g.NewGraphite(config.GraphiteHost, 60*time.Second, 10*time.Second)
		if err != nil {
			log.Fatalf("unable to connect to to graphite: %v: %v", config.GraphiteHost, err)
		}

		hostname, _ := os.Hostname()
		hostname = strings.Replace(hostname, ".", "_", -1)

		//		graphite.Register(fmt.Sprintf("carbon.writer.%s.metricsReceived",
		//			hostname), Metrics.received)

		for i := 0; i <= config.Buckets; i++ {
			graphite.Register(fmt.Sprintf("carbon.writer.%s.write_in_%dms_to_%dms", hostname, i*100, (i+1)*100), bucketEntry(i))
		}
	}

	logger.Logf("listening on %s, statistics via %s", *addr, *reportaddr)
	go listenAndServe(*addr, schemas, aggrs)
	err = http.ListenAndServe(*reportaddr, nil)
	if err != nil {
		log.Fatalf("%s", err)
//.........这里部分代码省略.........
开发者ID:tehmaze-labs,项目名称:carbonwriter,代码行数:101,代码来源:main.go


示例20: main

func main() {

	flag.Usage = usage
	flag.Parse()

	config_file = "/etc/carbon-relay-ng.ini"
	if 1 == flag.NArg() {
		config_file = flag.Arg(0)
	}

	if _, err := toml.DecodeFile(config_file, &config); err != nil {
		log.Error("Cannot use config file '%s':\n", config_file)
		log.Error(err.Error())
		usage()
		return
	}
	//runtime.SetBlockProfileRate(1) // to enable block profiling. in my experience, adds 35% overhead.

	levels := map[string]logging.Level{
		"critical": logging.CRITICAL,
		"error":    logging.ERROR,
		"warning":  logging.WARNING,
		"notice":   logging.NOTICE,
		"info":     logging.INFO,
		"debug":    logging.DEBUG,
	}
	level, ok := levels[config.Log_level]
	if !ok {
		log.Error("unrecognized log level '%s'\n", config.Log_level)
		return
	}
	logging.SetLevel(level, "carbon-relay-ng")
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	if len(config.Instance) == 0 {
		log.Error("instance identifier cannot be empty")
		os.Exit(1)
	}

	runtime.GOMAXPROCS(config.max_procs)

	instance = config.Instance
	expvar.NewString("instance").Set(instance)
	expvar.NewString("service").Set(service)

	log.Notice("===== carbon-relay-ng instance '%s' starting. =====\n", instance)

	numIn = Counter("unit=Metric.direction=in")
	numInvalid = Counter("unit=Err.type=invalid")
	if config.Instrumentation.Graphite_addr != "" {
		addr, err := net.ResolveTCPAddr("tcp", config.Instrumentation.Graphite_addr)
		if err != nil {
			log.Fatal(err)
		}
		go metrics.Graphite(metrics.DefaultRegistry, time.Duration(config.Instrumentation.Graphite_interval)*time.Millisecond, "", addr)
	}

	log.Notice("creating routing table...")
	maxAge, err := time.ParseDuration(config.Bad_metrics_max_age)
	if err != nil {
		log.Error("could not parse badMetrics max age")
		log.Error(err.Error())
		os.Exit(1)
	}
	badMetrics = badmetrics.New(maxAge)
	table = NewTable(config.Spool_dir)
	log.Notice("initializing routing table...")
	for i, cmd := range config.Init {
		log.Notice("applying: %s", cmd)
		err = applyCommand(table, cmd)
		if err != nil {
			log.Error("could not apply init cmd #%d", i+1)
			log.Error(err.Error())
			os.Exit(1)
		}
	}
	tablePrinted := table.Print()
	log.Notice("===========================")
	log.Notice("========== TABLE ==========")
	log.Notice("===========================")
	for _, line := range strings.Split(tablePrinted, "\n") {
		log.Notice(line)
	}

	// Follow the goagain protocol, <https://github.com/rcrowley/goagain>.
	l, ppid, err := goagain.GetEnvs()
	if nil != err {
		laddr, err := net.ResolveTCPAddr("tcp", config.Listen_addr)
		if nil != err {
			log.Error(err.Error())
			os.Exit(1)
		}
		l, err = net.ListenTCP("tcp", laddr)
//.........这里部分代码省略.........
开发者ID:rtkrruvinskiy,项目名称:carbon-relay-ng,代码行数:101,代码来源:carbon-relay-ng.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang expvar.Publish函数代码示例发布时间:2022-05-24
下一篇:
Golang expvar.NewMap函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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