Units
The go-metrics
package provides a way to specify units for all metrics. This ensures consistency and clarity in understanding the data. Units are important because they provide context for the values of the metrics. For example, a metric that measures the number of requests per second is much more meaningful if it is specified as “requests/second” than if it is simply specified as “requests”.
Standard Units
The go-metrics
package provides a set of standard units that can be used to specify the units of metrics. These units are defined in the units.go
file. units.go
package metrics
// Unit is an interface that represents a unit of measurement.
type Unit interface {
// String returns the string representation of the unit.
String() string
}
// TimeUnit is a unit of time.
type TimeUnit interface {
Unit
// Seconds returns the number of seconds in the unit.
Seconds() float64
}
// ByteUnit is a unit of byte size.
type ByteUnit interface {
Unit
// Bytes returns the number of bytes in the unit.
Bytes() float64
}
// Units
var (
Nanoseconds TimeUnit = nanoseconds{}
Microseconds TimeUnit = microseconds{}
Milliseconds TimeUnit = milliseconds{}
Seconds TimeUnit = seconds{}
Minutes TimeUnit = minutes{}
Hours TimeUnit = hours{}
Days TimeUnit = days{}
Bytes ByteUnit = bytes{}
Kilobytes ByteUnit = kilobytes{}
Megabytes ByteUnit = megabytes{}
Gigabytes ByteUnit = gigabytes{}
Terabytes ByteUnit = terabytes{}
Petabytes ByteUnit = petabytes{}
Exabytes ByteUnit = exabytes{}
)
Examples
// Create a metric that measures the number of requests per second.
requestsPerSecond := NewCounter()
requestsPerSecond.SetUnit(metrics.PerSecond)
// Create a metric that measures the average response time in milliseconds.
averageResponseTime := NewGauge()
averageResponseTime.SetUnit(metrics.Milliseconds)
// Create a metric that measures the number of bytes transferred per minute.
bytesTransferredPerMinute := NewGauge()
bytesTransferredPerMinute.SetUnit(metrics.PerMinute)
bytesTransferredPerMinute.SetUnit(metrics.Bytes)
Extending Units
If the standard units provided by the go-metrics
package do not meet your needs, you can extend the Unit
interface by creating your own custom unit types.
// Custom unit for measuring the number of widgets per hour.
type WidgetsPerHour struct{}
func (u WidgetsPerHour) String() string {
return "widgets/hour"
}
// Create a metric that measures the number of widgets produced per hour.
widgetsProducedPerHour := NewCounter()
widgetsProducedPerHour.SetUnit(WidgetsPerHour{})