Home  >  Article  >  Backend Development  >  How to create tsdb wal or block programmatically for Prometheus

How to create tsdb wal or block programmatically for Prometheus

PHPz
PHPzforward
2024-02-06 08:40:03645browse

如何以编程方式为 Prometheus 创建 tsdb wal 或块

Question content

I need to generate sample data for Prometheus and am trying to create a script to create a tsdb chunk programmatically. With the help of ChatGPT I wrote this code and it creates the WAL block that Prometheus accepts and even creates the autocomplete detected series name but I don't see any value, why?

package main

import (
    "context"
    "fmt"
    "github.com/prometheus/prometheus/model/labels"
    "github.com/prometheus/prometheus/storage"
    "github.com/prometheus/prometheus/tsdb"
    "os"
    "time"
)

func main() {
    // Create a new TSDB instance
    db, err := tsdb.Open(
        "./data", // directory where the data will be stored
        nil,      // a logger (can be nil for no logging)
        nil,      // an optional prometheus.Registerer
        tsdb.DefaultOptions(),
        nil,
    )
    if err != nil {
        fmt.Println("Error opening TSDB:", err)
        os.Exit(1)
    }
    defer db.Close()

    // Create a new appender
    app := db.Appender(context.Background())

    // Create labels for the gauge time series
    lbls := labels.FromStrings("__name__", "example_gauge", "type", "gauge")

    // Initialize a SeriesRef
    var ref storage.SeriesRef

    // Add some data points
    for i := 0; i < 10; i++ {
        var err error
        ref, err = app.Append(ref, lbls, time.Now().Unix()+int64(i), float64(i))
        if err != nil {
            fmt.Println("Error appending:", err)
            os.Exit(1)
        }
    }

    // Commit the data
    err = app.Commit()
    if err != nil {
        fmt.Println("Error committing:", err)
        os.Exit(1)
    }
}

Correct answer


Okay the above code works, the only problem is that I need to pass the time in milliseconds and time.Now ().Unix() returns it in seconds, so you need to multiply it by 1000, so changing this line will give you the result:

From:

ref, err = app.Append(ref, lbls, time.Now().Unix()+int64(i), float64(i))

to:

ref, err = app.Append(ref, lbls, (time.Now().Unix()+int64(i)) * 1000, float64(i))

The above is the detailed content of How to create tsdb wal or block programmatically for Prometheus. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete