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

How to create tsdb wal or block programmatically for Prometheus

PHPz
Release: 2024-02-06 08:40:03
forward
701 people have browsed it

如何以编程方式为 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)
    }
}
Copy after login


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))
Copy after login

to:

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template