Skip to content

Commit

Permalink
Initialize counter created timestamp during metric initialization
Browse files Browse the repository at this point in the history
Signed-off-by: Arthur Silva Sens <arthur.sens@coralogix.com>
  • Loading branch information
ArthurSens committed Aug 1, 2023
1 parent 05c3813 commit 8e4f899
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
12 changes: 5 additions & 7 deletions prometheus/counter.go
Expand Up @@ -93,6 +93,7 @@ func NewCounter(opts CounterOpts) Counter {
)
result := &counter{desc: desc, labelPairs: desc.constLabelPairs, now: time.Now}
result.init(result) // Init self-collection.
result.initCreated()
return result
}

Expand All @@ -114,6 +115,10 @@ type counter struct {
now func() time.Time // To mock out time.Now() for testing.
}

func (c *counter) initCreated() {
c.createdTs = timestamppb.New(c.now())
}

func (c *counter) Desc() *Desc {
return c.desc
}
Expand All @@ -123,10 +128,6 @@ func (c *counter) Add(v float64) {
panic(errors.New("counter cannot decrease in value"))
}

if c.createdTs == nil {
c.createdTs = timestamppb.New(c.now())
}

ival := uint64(v)
if float64(ival) == v {
atomic.AddUint64(&c.valInt, ival)
Expand All @@ -149,9 +150,6 @@ func (c *counter) AddWithExemplar(v float64, e Labels) {

func (c *counter) Inc() {
atomic.AddUint64(&c.valInt, 1)
if c.createdTs == nil {
c.createdTs = timestamppb.New(c.now())
}
}

func (c *counter) get() float64 {
Expand Down
27 changes: 26 additions & 1 deletion prometheus/counter_test.go
Expand Up @@ -282,6 +282,32 @@ func TestCounterCreatedTimestamp(t *testing.T) {
Help: "test help",
}).(*counter)
counter.now = func() time.Time { return now }
counter.initCreated()

ts := timestamppb.New(now)
if err := ts.CheckValid(); err != nil {
t.Fatal(err)
}

expectedCounter := &dto.Counter{
CreatedTimestamp: ts,
}

if counter.createdTs.AsTime() != expectedCounter.CreatedTimestamp.AsTime() {
t.Errorf("expected created timestamp %s, got %s", expectedCounter.CreatedTimestamp, counter.createdTs)
}
}

func TestCounterVecCreatedTimestamp(t *testing.T) {
now := time.Now()

counterVec := NewCounterVec(CounterOpts{
Name: "test",
Help: "test help",
}, []string{"label"})
counter := counterVec.WithLabelValues("value").(*counter)
counter.now = func() time.Time { return now }
counter.initCreated()

ts := timestamppb.New(now)
if err := ts.CheckValid(); err != nil {
Expand All @@ -292,7 +318,6 @@ func TestCounterCreatedTimestamp(t *testing.T) {
CreatedTimestamp: ts,
}

counter.Inc()
if counter.createdTs.AsTime() != expectedCounter.CreatedTimestamp.AsTime() {
t.Errorf("expected created timestamp %s, got %s", expectedCounter.CreatedTimestamp, counter.createdTs)
}
Expand Down

0 comments on commit 8e4f899

Please sign in to comment.