本文整理汇总了Golang中github.com/prometheus/common/log.Infof函数的典型用法代码示例。如果您正苦于以下问题:Golang Infof函数的具体用法?Golang Infof怎么用?Golang Infof使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Infof函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: rebuildLabelIndexes
func (p *persistence) rebuildLabelIndexes(
fpToSeries map[model.Fingerprint]*memorySeries,
) error {
count := 0
log.Info("Rebuilding label indexes.")
log.Info("Indexing metrics in memory.")
for fp, s := range fpToSeries {
p.indexMetric(fp, s.metric)
count++
if count%10000 == 0 {
log.Infof("%d metrics queued for indexing.", count)
}
}
log.Info("Indexing archived metrics.")
var fp codable.Fingerprint
var m codable.Metric
if err := p.archivedFingerprintToMetrics.ForEach(func(kv index.KeyValueAccessor) error {
if err := kv.Key(&fp); err != nil {
return err
}
if err := kv.Value(&m); err != nil {
return err
}
p.indexMetric(model.Fingerprint(fp), model.Metric(m))
count++
if count%10000 == 0 {
log.Infof("%d metrics queued for indexing.", count)
}
return nil
}); err != nil {
return err
}
log.Info("All requests for rebuilding the label indexes queued. (Actual processing may lag behind.)")
return nil
}
示例2: runShard
func (t *StorageQueueManager) runShard(i int) {
defer t.wg.Done()
shard := t.shards[i]
// Send batches of at most MaxSamplesPerSend samples to the remote storage.
// If we have fewer samples than that, flush them out after a deadline
// anyways.
pendingSamples := model.Samples{}
for {
select {
case s, ok := <-shard:
if !ok {
if len(pendingSamples) > 0 {
log.Infof("Flushing %d samples to remote storage...", len(pendingSamples))
t.sendSamples(pendingSamples)
log.Infof("Done flushing.")
}
return
}
pendingSamples = append(pendingSamples, s)
for len(pendingSamples) >= t.cfg.MaxSamplesPerSend {
t.sendSamples(pendingSamples[:t.cfg.MaxSamplesPerSend])
pendingSamples = pendingSamples[t.cfg.MaxSamplesPerSend:]
}
case <-time.After(t.cfg.BatchSendDeadline):
if len(pendingSamples) > 0 {
t.sendSamples(pendingSamples)
pendingSamples = pendingSamples[:0]
}
}
}
}
示例3: Run
// Run continuously sends samples to the remote storage.
func (t *StorageQueueManager) Run() {
defer func() {
close(t.drained)
}()
// Send batches of at most maxSamplesPerSend samples to the remote storage.
// If we have fewer samples than that, flush them out after a deadline
// anyways.
for {
select {
case s, ok := <-t.queue:
if !ok {
log.Infof("Flushing %d samples to remote storage...", len(t.pendingSamples))
t.flush()
log.Infof("Done flushing.")
return
}
t.pendingSamples = append(t.pendingSamples, s)
for len(t.pendingSamples) >= maxSamplesPerSend {
t.sendSamples(t.pendingSamples[:maxSamplesPerSend])
t.pendingSamples = t.pendingSamples[maxSamplesPerSend:]
}
case <-time.After(batchSendDeadline):
t.flush()
}
}
}
示例4: main
func main() {
flag.Parse()
if *printCollectors {
collectorNames := make(sort.StringSlice, 0, len(collector.Factories))
for n := range collector.Factories {
collectorNames = append(collectorNames, n)
}
collectorNames.Sort()
fmt.Printf("Available collectors:\n")
for _, n := range collectorNames {
fmt.Printf(" - %s\n", n)
}
return
}
collectors, err := loadCollectors()
if err != nil {
log.Fatalf("Couldn't load collectors: %s", err)
}
log.Infof("Enabled collectors:")
for n := range collectors {
log.Infof(" - %s", n)
}
nodeCollector := NodeCollector{collectors: collectors}
prometheus.MustRegister(nodeCollector)
sigUsr1 := make(chan os.Signal)
signal.Notify(sigUsr1, syscall.SIGUSR1)
handler := prometheus.Handler()
if *authUser != "" || *authPass != "" {
if *authUser == "" || *authPass == "" {
log.Fatal("You need to specify -auth.user and -auth.pass to enable basic auth")
}
handler = &basicAuthHandler{
handler: prometheus.Handler().ServeHTTP,
user: *authUser,
password: *authPass,
}
}
http.Handle(*metricsPath, handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Node Exporter</title></head>
<body>
<h1>Node Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
log.Infof("Starting node_exporter v%s at %s", Version, *listenAddress)
err = http.ListenAndServe(*listenAddress, nil)
if err != nil {
log.Fatal(err)
}
}
示例5: main
func main() {
var (
listenAddress = flag.String("web.listen-address", ":9100", "Address on which to expose metrics and web interface.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
enabledCollectors = flag.String("collectors.enabled", filterAvailableCollectors(defaultCollectors), "Comma-separated list of collectors to use.")
printCollectors = flag.Bool("collectors.print", false, "If true, print available collectors and exit.")
)
flag.Parse()
if *printCollectors {
collectorNames := make(sort.StringSlice, 0, len(collector.Factories))
for n := range collector.Factories {
collectorNames = append(collectorNames, n)
}
collectorNames.Sort()
fmt.Printf("Available collectors:\n")
for _, n := range collectorNames {
fmt.Printf(" - %s\n", n)
}
return
}
collectors, err := loadCollectors(*enabledCollectors)
if err != nil {
log.Fatalf("Couldn't load collectors: %s", err)
}
log.Infof("Enabled collectors:")
for n := range collectors {
log.Infof(" - %s", n)
}
nodeCollector := NodeCollector{collectors: collectors}
prometheus.MustRegister(nodeCollector)
handler := prometheus.Handler()
http.Handle(*metricsPath, handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Node Exporter</title></head>
<body>
<h1>Node Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
log.Infof("Starting node_exporter v%s at %s", Version, *listenAddress)
err = http.ListenAndServe(*listenAddress, nil)
if err != nil {
log.Fatal(err)
}
}
示例6: parseTinystatsFile
func parseTinystatsFile() {
if *ipv4TinystatsFile != "disabled" {
statsFile, err := os.Open(*ipv4TinystatsFile)
if err != nil {
log.Infof("error opening file, skipping: %s", *ipv4TinystatsFile)
} else {
reader := bufio.NewReader(statsFile)
line, err := reader.ReadString('\n')
if err == nil {
q := strings.Split(line, ":")
ipv4QueryA, ipv4QueryNS, ipv4QueryCNAME,
ipv4QuerySOA, ipv4QueryPTR, ipv4QueryHINFO,
ipv4QueryMX, ipv4QueryTXT, ipv4QueryRP,
ipv4QuerySIG, ipv4QueryKEY, ipv4QueryAAAA,
ipv4QueryAXFR, ipv4QueryANY, ipv4QueryTOTAL,
ipv4QueryOTHER, ipv4QueryNOTAUTH, ipv4QueryNOTIMPL,
ipv4QueryBADCLASS, ipv4QueryNOQUERY = q[0], q[1],
q[2], q[3], q[4], q[5], q[6], q[7], q[8],
q[9], q[10], q[11], q[12], q[13], q[14],
q[15], q[16], q[17], q[18], q[19]
statsFile.Close()
}
}
}
if *ipv6TinystatsFile != "disabled" {
statsFile, err := os.Open(*ipv6TinystatsFile)
if err != nil {
log.Infof("error opening file, skipping: %s", *ipv6TinystatsFile)
} else {
reader := bufio.NewReader(statsFile)
line, err := reader.ReadString('\n')
if err == nil {
q := strings.Split(line, ":")
ipv6QueryA, ipv6QueryNS, ipv6QueryCNAME,
ipv6QuerySOA, ipv6QueryPTR, ipv6QueryHINFO,
ipv6QueryMX, ipv6QueryTXT, ipv6QueryRP,
ipv6QuerySIG, ipv6QueryKEY, ipv6QueryAAAA,
ipv6QueryAXFR, ipv6QueryANY, ipv6QueryTOTAL,
ipv6QueryOTHER, ipv6QueryNOTAUTH, ipv6QueryNOTIMPL,
ipv6QueryBADCLASS, ipv6QueryNOQUERY = q[0], q[1],
q[2], q[3], q[4], q[5], q[6], q[7], q[8],
q[9], q[10], q[11], q[12], q[13], q[14],
q[15], q[16], q[17], q[18], q[19]
statsFile.Close()
}
}
}
}
示例7: scrapeApps
func (e *Exporter) scrapeApps(json *gabs.Container, ch chan<- prometheus.Metric) {
elements, _ := json.S("apps").Children()
states := map[string]string{
"running": "tasksRunning",
"staged": "tasksStaged",
"healthy": "tasksHealthy",
"unhealthy": "tasksUnhealthy",
"cpus": "cpus",
"mem_in_mb": "mem",
"disk_in_mb": "disk",
"gpus": "gpus",
"avg_uptime": "taskStats.startedAfterLastScaling.stats.lifeTime.averageSeconds",
}
name := "app_instances"
gauge, new := e.Gauges.Fetch(name, "Marathon app instance count", "app")
if new {
log.Infof("Added gauge %q\n", name)
}
gauge.Reset()
for _, app := range elements {
id := app.Path("id").Data().(string)
data := app.Path("instances").Data()
count, ok := data.(float64)
if !ok {
log.Debugf(fmt.Sprintf("Bad conversion! Unexpected value \"%v\" for number of app instances\n", data))
continue
}
gauge.WithLabelValues(id).Set(count)
for key, value := range states {
name := fmt.Sprintf("app_task_%s", key)
gauge, new := e.Gauges.Fetch(name, fmt.Sprintf("Marathon app task %s count", key), "app")
if new {
log.Infof("Added gauge %q\n", name)
}
data := app.Path(value).Data()
count, ok := data.(float64)
if !ok {
log.Debugf(fmt.Sprintf("Bad conversion! Unexpected value \"%v\" for number of \"%s\" tasks\n", data, key))
continue
}
gauge.WithLabelValues(id).Set(count)
}
}
}
示例8: reloadConfig
func reloadConfig(filename string, rls ...Reloadable) (err error) {
log.Infof("Loading configuration file %s", filename)
defer func() {
if err == nil {
configSuccess.Set(1)
configSuccessTime.Set(float64(time.Now().Unix()))
} else {
configSuccess.Set(0)
}
}()
conf, err := config.LoadFile(filename)
if err != nil {
return fmt.Errorf("couldn't load configuration (-config.file=%s): %v", filename, err)
}
failed := false
for _, rl := range rls {
if err := rl.ApplyConfig(conf); err != nil {
log.Error("Failed to apply configuration: ", err)
failed = true
}
}
if failed {
return fmt.Errorf("one or more errors occurred while applying the new configuration (-config.file=%s)", filename)
}
return nil
}
示例9: ListenAndServe
// ListenAndServe start the server
func ListenAndServe(addr string, core core.Core, fe fs.FileExplorer) {
log.Infof("REST listening at: http://%v", core.GetAddr())
clientHandlers := clientAPI.NewHandler(core)
mesosHandlers := mesosAPI.NewHandler(core)
fsHandlers := fsAPI.NewHandler(fe)
r := createRouter(core, clientHandlers, mesosHandlers, fsHandlers)
m := martini.New()
m.Use(cors.Allow(&cors.Options{
AllowOrigins: []string{"*"},
AllowMethods: []string{"POST", "GET", "PUT", "DELETE"},
AllowHeaders: []string{"Origin", "x-requested-with", "Content-Type", "Content-Range", "Content-Disposition", "Content-Description"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: false,
}))
m.Use(logger())
m.Use(recovery())
m.Use(martini.Static("static"))
m.Use(martini.Static("temp", martini.StaticOptions{
Prefix: "/context/",
}))
m.Use(martini.Static("executor", martini.StaticOptions{
Prefix: "/executor/",
}))
m.Action(r.Handle)
go m.RunOnAddr(addr)
}
示例10: reloadConfig
func reloadConfig(filename string, rls ...Reloadable) (err error) {
log.Infof("Loading configuration file %s", filename)
defer func() {
if err == nil {
configSuccess.Set(1)
configSuccessTime.Set(float64(time.Now().Unix()))
} else {
configSuccess.Set(0)
}
}()
conf, err := config.LoadFile(filename)
if err != nil {
return fmt.Errorf("couldn't load configuration (-config.file=%s): %v", filename, err)
}
// Apply all configs and return the first error if there were any.
for _, rl := range rls {
if err != nil {
err = rl.ApplyConfig(conf)
} else {
rl.ApplyConfig(conf)
}
}
return err
}
示例11: watchConfig
func watchConfig(fileName string, mapper *metricMapper) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
err = watcher.WatchFlags(fileName, fsnotify.FSN_MODIFY)
if err != nil {
log.Fatal(err)
}
for {
select {
case ev := <-watcher.Event:
log.Infof("Config file changed (%s), attempting reload", ev)
err = mapper.initFromFile(fileName)
if err != nil {
log.Errorln("Error reloading config:", err)
configLoads.WithLabelValues("failure").Inc()
} else {
log.Infoln("Config reloaded successfully")
configLoads.WithLabelValues("success").Inc()
}
// Re-add the file watcher since it can get lost on some changes. E.g.
// saving a file with vim results in a RENAME-MODIFY-DELETE event
// sequence, after which the newly written file is no longer watched.
err = watcher.WatchFlags(fileName, fsnotify.FSN_MODIFY)
case err := <-watcher.Error:
log.Errorln("Error watching config:", err)
}
}
}
示例12: main
func main() {
var (
listenAddress = flag.String("listen-address", ":9120", "Address to listen on for web interface and telemetry.")
metricsPath = flag.String("metric-path", "/metrics", "Path under which to expose metrics.")
apiURL = flag.String("api-url", "http://localhost:8001/", "Base-URL of PowerDNS authoritative server/recursor API.")
apiKey = flag.String("api-key", "", "PowerDNS API Key")
)
flag.Parse()
hostURL, err := url.Parse(*apiURL)
if err != nil {
log.Fatalf("Error parsing api-url: %v", err)
}
server, err := getServerInfo(hostURL, *apiKey)
if err != nil {
log.Fatalf("Could not fetch PowerDNS server info: %v", err)
}
exporter := NewExporter(*apiKey, server.DaemonType, hostURL)
prometheus.MustRegister(exporter)
log.Infof("Starting Server: %s", *listenAddress)
http.Handle(*metricsPath, prometheus.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>PowerDNS Exporter</title></head>
<body>
<h1>PowerDNS Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
示例13: pduValueAsString
// This mirrors decodeValue in gosnmp's helper.go.
func pduValueAsString(pdu *gosnmp.SnmpPDU) string {
switch pdu.Value.(type) {
case int:
return strconv.Itoa(pdu.Value.(int))
case uint:
return strconv.FormatUint(uint64(pdu.Value.(uint)), 10)
case int64:
return strconv.FormatInt(pdu.Value.(int64), 10)
case string:
if pdu.Type == gosnmp.ObjectIdentifier {
// Trim leading period.
return pdu.Value.(string)[1:]
}
return pdu.Value.(string)
case []byte:
// OctetString
return string(pdu.Value.([]byte))
case nil:
return ""
default:
// This shouldn't happen.
log.Infof("Got PDU with unexpected type: Name: %s Value: '%s', Go Type: %T SNMP Type: %s", pdu.Name, pdu.Value, pdu.Value, pdu.Type)
snmpUnexpectedPduType.Inc()
return fmt.Sprintf("%s", pdu.Value)
}
}
示例14: reloadConfig
func reloadConfig(filename string, rls ...Reloadable) (success bool) {
log.Infof("Loading configuration file %s", filename)
defer func() {
if success {
configSuccess.Set(1)
configSuccessTime.Set(float64(time.Now().Unix()))
} else {
configSuccess.Set(0)
}
}()
conf, err := config.LoadFile(filename)
if err != nil {
log.Errorf("Couldn't load configuration (-config.file=%s): %v", filename, err)
// TODO(julius): Remove this notice when releasing 0.17.0 or 0.18.0.
if err.Error() == "unknown fields in global config: labels" {
log.Errorf("NOTE: The 'labels' setting in the global configuration section has been renamed to 'external_labels' and now has changed semantics (see release notes at https://github.com/prometheus/prometheus/blob/master/CHANGELOG.md). Please update your configuration file accordingly.")
}
return false
}
success = true
for _, rl := range rls {
success = success && rl.ApplyConfig(conf)
}
return success
}
示例15: main
func main() {
flag.Parse()
if *printCollectors {
collectorNames := make(sort.StringSlice, 0, len(collector.Factories))
for n := range collector.Factories {
collectorNames = append(collectorNames, n)
}
collectorNames.Sort()
fmt.Printf("Available collectors:\n")
for _, n := range collectorNames {
fmt.Printf(" - %s\n", n)
}
return
}
collectors, err := loadCollectors()
if err != nil {
log.Fatalf("Couldn't load collectors: %s", err)
}
log.Infof("Enabled collectors:")
for n := range collectors {
log.Infof(" - %s", n)
}
nodeCollector := NodeCollector{collectors: collectors}
prometheus.MustRegister(nodeCollector)
handler := prometheus.Handler()
http.Handle(*metricsPath, handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Node Exporter</title></head>
<body>
<h1>Node Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
log.Infof("Starting node_exporter v%s at %s", Version, *listenAddress)
err = http.ListenAndServe(*listenAddress, nil)
if err != nil {
log.Fatal(err)
}
}