Complete API reference for the TelemetryFlow Go SDK.
import "github.com/telemetryflow/telemetryflow-go-sdk/pkg/telemetryflow"The main package provides the public API for interacting with TelemetryFlow.
graph TB
subgraph "TelemetryFlow Go SDK API"
subgraph "Interface Layer"
CLIENT[Client]
BUILDER[Builder]
end
subgraph "Domain Layer"
CREDS[Credentials]
CONFIG[TelemetryConfig]
PROTO[Protocol]
SIGNAL[SignalType]
end
subgraph "Application Layer"
CMDS[Commands]
QRYS[Queries]
end
end
CLIENT --> CONFIG
CLIENT --> CMDS
CLIENT --> QRYS
BUILDER --> CONFIG
CONFIG --> CREDS
CONFIG --> PROTO
CONFIG --> SIGNAL
The Client struct is the main entry point for sending telemetry data.
type Client struct {
// contains filtered or unexported fields
}Creates a new TelemetryFlow client from a configuration.
func NewClient(config *domain.TelemetryConfig) (*Client, error)Parameters:
| Name | Type | Description |
|---|---|---|
config |
*domain.TelemetryConfig |
The telemetry configuration |
Returns:
| Type | Description |
|---|---|
*Client |
The configured client |
error |
Error if configuration is invalid |
Example:
config, _ := domain.NewTelemetryConfig(creds, "api.telemetryflow.id:4317", "my-service")
client, err := telemetryflow.NewClient(config)
if err != nil {
log.Fatal(err)
}Creates a client from environment variables.
func NewFromEnv() (*Client, error)Environment Variables:
| Variable | Required | Default | Description |
|---|---|---|---|
TELEMETRYFLOW_API_KEY_ID |
Yes | - | API key ID (format: tfk_...) |
TELEMETRYFLOW_API_KEY_SECRET |
Yes | - | API key secret (format: tfs_...) |
TELEMETRYFLOW_ENDPOINT |
No | api.telemetryflow.id:4317 |
OTLP endpoint |
TELEMETRYFLOW_SERVICE_NAME |
No | unknown-service |
Service name |
TELEMETRYFLOW_SERVICE_VERSION |
No | 1.2.0 |
Service version |
ENV or ENVIRONMENT |
No | production |
Deployment environment |
Example:
client, err := telemetryflow.NewFromEnv()
if err != nil {
log.Fatal(err)
}Creates a client from environment variables, panics on error.
func MustNewFromEnv() *ClientExample:
client := telemetryflow.MustNewFromEnv()Creates a client with minimal configuration.
func NewSimple(apiKeyID, apiKeySecret, endpoint, serviceName string) (*Client, error)Parameters:
| Name | Type | Description |
|---|---|---|
apiKeyID |
string |
API key ID |
apiKeySecret |
string |
API key secret |
endpoint |
string |
OTLP endpoint |
serviceName |
string |
Service name |
Example:
client, err := telemetryflow.NewSimple(
"tfk_your_key",
"tfs_your_secret",
"api.telemetryflow.id:4317",
"my-service",
)Creates a client with minimal configuration, panics on error.
func MustNewSimple(apiKeyID, apiKeySecret, endpoint, serviceName string) *ClientInitializes the SDK and starts exporters.
func (c *Client) Initialize(ctx context.Context) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Context for initialization |
Returns:
| Type | Description |
|---|---|
error |
Error if initialization fails or already initialized |
Example:
ctx := context.Background()
if err := client.Initialize(ctx); err != nil {
log.Fatal(err)
}Gracefully shuts down the SDK.
func (c *Client) Shutdown(ctx context.Context) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Context for shutdown (respects deadline) |
Example:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client.Shutdown(ctx)Forces a flush of all pending telemetry.
func (c *Client) Flush(ctx context.Context) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Context for flush operation |
Example:
if err := client.Flush(ctx); err != nil {
log.Printf("Flush failed: %v", err)
}Returns whether the client is initialized.
func (c *Client) IsInitialized() boolReturns the client configuration.
func (c *Client) Config() *domain.TelemetryConfigRecords a generic metric.
func (c *Client) RecordMetric(ctx context.Context, name string, value float64, unit string, attributes map[string]interface{}) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
name |
string |
Metric name |
value |
float64 |
Metric value |
unit |
string |
Unit of measurement (e.g., "s", "ms", "bytes") |
attributes |
map[string]interface{} |
Additional attributes |
Example:
client.RecordMetric(ctx, "request.size", 1024.0, "bytes", map[string]interface{}{
"endpoint": "/api/users",
})Increments a counter metric.
func (c *Client) IncrementCounter(ctx context.Context, name string, value int64, attributes map[string]interface{}) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
name |
string |
Counter name |
value |
int64 |
Increment value |
attributes |
map[string]interface{} |
Additional attributes |
Example:
client.IncrementCounter(ctx, "http.requests.total", 1, map[string]interface{}{
"method": "GET",
"status": 200,
"path": "/api/users",
})Records a gauge metric (point-in-time value).
func (c *Client) RecordGauge(ctx context.Context, name string, value float64, attributes map[string]interface{}) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
name |
string |
Gauge name |
value |
float64 |
Current value |
attributes |
map[string]interface{} |
Additional attributes |
Example:
client.RecordGauge(ctx, "memory.usage", 512.5, map[string]interface{}{
"unit": "MB",
"host": "server-01",
})Records a histogram measurement (for distributions).
func (c *Client) RecordHistogram(ctx context.Context, name string, value float64, unit string, attributes map[string]interface{}) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
name |
string |
Histogram name |
value |
float64 |
Measured value |
unit |
string |
Unit of measurement |
attributes |
map[string]interface{} |
Additional attributes |
Example:
client.RecordHistogram(ctx, "http.request.duration", 0.125, "s", map[string]interface{}{
"method": "POST",
"endpoint": "/api/orders",
})Emits a structured log entry with custom severity.
func (c *Client) Log(ctx context.Context, severity string, message string, attributes map[string]interface{}) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
severity |
string |
Log severity ("debug", "info", "warn", "error") |
message |
string |
Log message |
attributes |
map[string]interface{} |
Additional attributes |
Emits an info-level log.
func (c *Client) LogInfo(ctx context.Context, message string, attributes map[string]interface{}) errorExample:
client.LogInfo(ctx, "User logged in successfully", map[string]interface{}{
"user_id": "12345",
"ip": "192.168.1.1",
"user_agent": "Mozilla/5.0...",
})Emits a warning-level log.
func (c *Client) LogWarn(ctx context.Context, message string, attributes map[string]interface{}) errorExample:
client.LogWarn(ctx, "High memory usage detected", map[string]interface{}{
"usage_mb": 850,
"threshold_mb": 800,
"action": "scaling recommended",
})Emits an error-level log.
func (c *Client) LogError(ctx context.Context, message string, attributes map[string]interface{}) errorExample:
client.LogError(ctx, "Database connection failed", map[string]interface{}{
"error": "connection timeout",
"host": "db.example.com",
"port": 5432,
"retries": 3,
})Starts a new trace span.
func (c *Client) StartSpan(ctx context.Context, name string, kind string, attributes map[string]interface{}) (string, error)Parameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
name |
string |
Span name |
kind |
string |
Span kind ("internal", "server", "client", "producer", "consumer") |
attributes |
map[string]interface{} |
Span attributes |
Returns:
| Type | Description |
|---|---|
string |
Span ID for later reference |
error |
Error if span creation fails |
Span Kinds:
| Kind | Description |
|---|---|
internal |
Internal operation |
server |
Server-side handler |
client |
Client-side request |
producer |
Message producer |
consumer |
Message consumer |
Example:
spanID, err := client.StartSpan(ctx, "process-payment", "internal", map[string]interface{}{
"payment_id": "pay_12345",
"payment_method": "credit_card",
"amount": 99.99,
})
if err != nil {
log.Printf("Failed to start span: %v", err)
}
defer client.EndSpan(ctx, spanID, nil)Ends an active span.
func (c *Client) EndSpan(ctx context.Context, spanID string, err error) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
spanID |
string |
Span ID returned from StartSpan |
err |
error |
Optional error to record (nil for success) |
Example:
// Success case
client.EndSpan(ctx, spanID, nil)
// Error case
client.EndSpan(ctx, spanID, fmt.Errorf("payment declined"))Adds an event to an active span.
func (c *Client) AddSpanEvent(ctx context.Context, spanID string, name string, attributes map[string]interface{}) errorParameters:
| Name | Type | Description |
|---|---|---|
ctx |
context.Context |
Request context |
spanID |
string |
Span ID |
name |
string |
Event name |
attributes |
map[string]interface{} |
Event attributes |
Example:
spanID, _ := client.StartSpan(ctx, "checkout", "server", nil)
// Add events during the span
client.AddSpanEvent(ctx, spanID, "cart.validated", map[string]interface{}{
"items_count": 3,
})
client.AddSpanEvent(ctx, spanID, "payment.processed", map[string]interface{}{
"provider": "stripe",
})
client.EndSpan(ctx, spanID, nil)The Builder provides a fluent interface for creating clients.
type Builder struct {
// contains filtered or unexported fields
}func NewBuilder() *BuilderExample:
builder := telemetryflow.NewBuilder()Sets the API credentials.
func (b *Builder) WithAPIKey(keyID, keySecret string) *BuilderReads API credentials from environment variables.
func (b *Builder) WithAPIKeyFromEnv() *BuilderReads from TELEMETRYFLOW_API_KEY_ID and TELEMETRYFLOW_API_KEY_SECRET.
Sets the OTLP endpoint.
func (b *Builder) WithEndpoint(endpoint string) *BuilderReads endpoint from environment variable.
func (b *Builder) WithEndpointFromEnv() *BuilderReads from TELEMETRYFLOW_ENDPOINT, defaults to api.telemetryflow.id:4317.
Sets the service name and version.
func (b *Builder) WithService(name, version string) *BuilderReads service info from environment variables.
func (b *Builder) WithServiceFromEnv() *BuilderSets the deployment environment.
func (b *Builder) WithEnvironment(env string) *BuilderReads environment from ENV or ENVIRONMENT variable.
func (b *Builder) WithEnvironmentFromEnv() *BuilderSets the OTLP protocol.
func (b *Builder) WithProtocol(protocol domain.Protocol) *BuilderSets the protocol to gRPC (default).
func (b *Builder) WithGRPC() *BuilderSets the protocol to HTTP.
func (b *Builder) WithHTTP() *BuilderEnables insecure connections (no TLS).
func (b *Builder) WithInsecure(insecure bool) *BuilderWarning: Only use for local development and testing.
Sets connection timeout.
func (b *Builder) WithTimeout(timeout time.Duration) *BuilderAdds a custom resource attribute.
func (b *Builder) WithCustomAttribute(key, value string) *BuilderExample:
builder.
WithCustomAttribute("team", "backend").
WithCustomAttribute("region", "us-east-1").
WithCustomAttribute("datacenter", "dc1")Configures from all environment variables.
func (b *Builder) WithAutoConfiguration() *BuilderEquivalent to calling all *FromEnv() methods.
Enables/disables specific signals.
func (b *Builder) WithSignals(metrics, logs, traces bool) *BuilderExample:
// Enable only metrics and traces
builder.WithSignals(true, false, true)Enables only metrics.
func (b *Builder) WithMetricsOnly() *BuilderEnables only logs.
func (b *Builder) WithLogsOnly() *BuilderEnables only traces.
func (b *Builder) WithTracesOnly() *BuilderCreates the TelemetryFlow client.
func (b *Builder) Build() (*Client, error)Creates the client and panics on error.
func (b *Builder) MustBuild() *Clientclient := telemetryflow.NewBuilder().
WithAPIKey("tfk_your_key_id", "tfs_your_secret").
WithEndpoint("api.telemetryflow.id:4317").
WithService("my-service", "1.0.0").
WithEnvironment("production").
WithGRPC().
WithSignals(true, true, true).
WithTimeout(30 * time.Second).
WithCustomAttribute("team", "backend").
WithCustomAttribute("region", "us-east-1").
MustBuild()Import the domain package for these types:
import "github.com/telemetryflow/telemetryflow-go-sdk/pkg/telemetryflow/domain"Represents TelemetryFlow API credentials (Value Object).
type Credentials struct {
// contains filtered or unexported fields
}func NewCredentials(keyID, keySecret string) (*Credentials, error)Validation:
keyIDmust start withtfk_keySecretmust start withtfs_
Methods:
| Method | Returns | Description |
|---|---|---|
KeyID() |
string |
Returns the API key ID |
KeySecret() |
string |
Returns the API key secret |
AuthorizationHeader() |
string |
Returns formatted auth header |
Equals(other *Credentials) |
bool |
Checks equality |
String() |
string |
Safe string representation (hides secret) |
Configuration aggregate root (Entity).
type TelemetryConfig struct {
// contains filtered or unexported fields
}func NewTelemetryConfig(credentials *Credentials, endpoint string, serviceName string) (*TelemetryConfig, error)Default Values:
| Setting | Default |
|---|---|
| Protocol | gRPC |
| Insecure | false |
| Timeout | 30s |
| Retry Enabled | true |
| Max Retries | 3 |
| Retry Backoff | 5s |
| Compression | true (gzip) |
| Metrics | enabled |
| Logs | enabled |
| Traces | enabled |
| Batch Timeout | 10s |
| Batch Max Size | 512 |
| Rate Limit | 1000 req/min |
Configuration Methods:
| Method | Parameters | Description |
|---|---|---|
WithProtocol(Protocol) |
Protocol | Set OTLP protocol |
WithInsecure(bool) |
enabled | Enable/disable TLS |
WithTimeout(Duration) |
timeout | Connection timeout |
WithRetry(bool, int, Duration) |
enabled, max, backoff | Retry configuration |
WithCompression(bool) |
enabled | Enable/disable gzip |
WithSignals(bool, bool, bool) |
metrics, logs, traces | Enable signals |
WithServiceVersion(string) |
version | Set service version |
WithEnvironment(string) |
env | Set environment |
WithCustomAttribute(string, string) |
key, value | Add custom attribute |
WithBatchSettings(Duration, int) |
timeout, maxSize | Batch configuration |
WithRateLimit(int) |
limit | Client-side rate limit |
Getter Methods:
| Method | Returns |
|---|---|
Credentials() |
*Credentials |
Endpoint() |
string |
Protocol() |
Protocol |
IsInsecure() |
bool |
Timeout() |
time.Duration |
IsRetryEnabled() |
bool |
MaxRetries() |
int |
RetryBackoff() |
time.Duration |
IsCompressionEnabled() |
bool |
ServiceName() |
string |
ServiceVersion() |
string |
Environment() |
string |
CustomAttributes() |
map[string]string |
BatchTimeout() |
time.Duration |
BatchMaxSize() |
int |
RateLimit() |
int |
IsSignalEnabled(SignalType) |
bool |
Validate() |
error |
OTLP protocol type.
type Protocol string
const (
ProtocolGRPC Protocol = "grpc"
ProtocolHTTP Protocol = "http"
)Telemetry signal type.
type SignalType string
const (
SignalMetrics SignalType = "metrics"
SignalLogs SignalType = "logs"
SignalTraces SignalType = "traces"
)Import the application package for these types:
import "github.com/telemetryflow/telemetryflow-go-sdk/pkg/telemetryflow/application"Commands represent intentions to change state.
| Command | Fields | Description |
|---|---|---|
RecordMetricCommand |
Name, Value, Unit, Attributes, Timestamp | Generic metric |
RecordCounterCommand |
Name, Value, Attributes | Counter increment |
RecordGaugeCommand |
Name, Value, Attributes | Gauge value |
RecordHistogramCommand |
Name, Value, Unit, Attributes | Histogram measurement |
| Command | Fields | Description |
|---|---|---|
EmitLogCommand |
Severity, Message, Attributes, Timestamp, TraceID, SpanID | Single log entry |
EmitBatchLogsCommand |
Logs []EmitLogCommand | Batch of logs |
| Command | Fields | Description |
|---|---|---|
StartSpanCommand |
Name, Kind, Attributes, ParentID | Start a span |
EndSpanCommand |
SpanID, Error | End a span |
AddSpanEventCommand |
SpanID, Name, Attributes, Timestamp | Add event to span |
| Command | Fields | Description |
|---|---|---|
InitializeSDKCommand |
Config | Initialize SDK |
ShutdownSDKCommand |
Timeout | Shutdown SDK |
FlushTelemetryCommand |
Timeout | Flush pending data |
Queries represent requests for data.
| Query | Fields | Result Type |
|---|---|---|
GetMetricQuery |
Name, StartTime, EndTime, GroupBy, Filters | MetricQueryResult |
AggregateMetricsQuery |
Name, StartTime, EndTime, Aggregation, GroupBy, Filters | AggregateMetricsResult |
| Query | Fields | Result Type |
|---|---|---|
GetLogsQuery |
StartTime, EndTime, Severity, SearchText, Filters, Limit, Offset | LogsQueryResult |
| Query | Fields | Result Type |
|---|---|---|
GetTraceQuery |
TraceID | TraceQueryResult |
SearchTracesQuery |
StartTime, EndTime, ServiceName, Operation, MinDuration, MaxDuration, Tags, HasError, Limit, Offset | TracesSearchResult |
| Query | Fields | Result Type |
|---|---|---|
GetHealthQuery |
- | HealthQueryResult |
GetSDKStatusQuery |
- | SDKStatusResult |
const (
ProtocolGRPC Protocol = "grpc"
ProtocolHTTP Protocol = "http"
)const (
SignalMetrics SignalType = "metrics"
SignalLogs SignalType = "logs"
SignalTraces SignalType = "traces"
)const (
SeverityDebug = "debug"
SeverityInfo = "info"
SeverityWarn = "warn"
SeverityError = "error"
)const (
SpanKindInternal = "internal"
SpanKindServer = "server"
SpanKindClient = "client"
SpanKindProducer = "producer"
SpanKindConsumer = "consumer"
)| Error | Cause | Solution |
|---|---|---|
client not initialized |
Calling methods before Initialize() | Call Initialize() first |
client already initialized |
Calling Initialize() twice | Only initialize once |
API key ID cannot be empty |
Missing API key ID | Provide valid API key |
invalid key ID format |
Key ID doesn't start with tfk_ |
Use correct format |
invalid key secret format |
Secret doesn't start with tfs_ |
Use correct format |
endpoint cannot be empty |
Missing endpoint | Provide endpoint URL |
service name cannot be empty |
Missing service name | Provide service name |
The SDK uses Go's error wrapping. Use errors.Is() and errors.As() for error checking:
if err := client.Initialize(ctx); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
log.Println("Initialization timed out")
}
log.Printf("Initialization failed: %v", err)
}func sendTelemetry(client *telemetryflow.Client) {
ctx := context.Background()
// Handle metric errors gracefully
if err := client.IncrementCounter(ctx, "requests", 1, nil); err != nil {
// Log but don't crash - telemetry is non-critical
log.Printf("Failed to record metric: %v", err)
}
// Always check span creation
spanID, err := client.StartSpan(ctx, "operation", "internal", nil)
if err != nil {
log.Printf("Failed to start span: %v", err)
return
}
defer func() {
if err := client.EndSpan(ctx, spanID, nil); err != nil {
log.Printf("Failed to end span: %v", err)
}
}()
// Your business logic...
}- Architecture Guide - Detailed architecture documentation
- Quickstart Guide - Getting started tutorial
- Examples - Complete usage examples
Built with care by the Telemetri Data Indonesia community