Documentation ¶
Overview ¶
Package traceflow provides a simple wrapper around OpenTelemetry to make it easier to create and manage traces.
Index ¶
- func Init(ctx context.Context, serviceName string, opts ...InitOption) (context.Context, func(context.Context), error)
- func UnaryClientInterceptor(trace *Trace) grpc.UnaryClientInterceptor
- type Attribute
- func AddBool(key string, value bool) Attribute
- func AddBoolSlice(key string, value []bool) Attribute
- func AddFloat(key string, value float64) Attribute
- func AddFloatSlice(key string, value []float64) Attribute
- func AddInt(key string, value int) Attribute
- func AddIntSlice(key string, value []int) Attribute
- func AddString(key, value string) Attribute
- func AddStringSlice(key string, value []string) Attribute
- type InitOption
- type Option
- type SpanContext
- type SpanKind
- type TelemetryBuilder
- type Trace
- func (t *Trace) AddAttribute(attrs ...Attribute) *Trace
- func (t *Trace) AddAttributeIf(cond bool, key string, value interface{}) *Trace
- func (t *Trace) AddCPUInfo() *Trace
- func (t *Trace) AddContainerInfo() *Trace
- func (t *Trace) AddCustomMetric(metricName string, value float64) *Trace
- func (t *Trace) AddDBColumnInfo(columnName string, columnCount int) *Trace
- func (t *Trace) AddDBConnectionInfo(connectionString string, connectionCount int) *Trace
- func (t *Trace) AddDBErrorInfo(errorMessage, errorCode string) *Trace
- func (t *Trace) AddDBIndexInfo(indexName string, indexCount int) *Trace
- func (t *Trace) AddDBInfo(dbName, dbVersion string) *Trace
- func (t *Trace) AddDBQuery(query, dbType string) *Trace
- func (t *Trace) AddDBTableInfo(tableName string, rowCount int) *Trace
- func (t *Trace) AddDBTransactionInfo(transactionID, status string) *Trace
- func (t *Trace) AddDiskInfo() *Trace
- func (t *Trace) AddError(err error) *Trace
- func (t *Trace) AddEvent(eventName string, timestamp time.Time) *Trace
- func (t *Trace) AddException(err error, stackTrace string) *Trace
- func (t *Trace) AddHTTPHeaders(headers http.Header) *Trace
- func (t *Trace) AddHTTPRequest(req *http.Request) *Trace
- func (t *Trace) AddHTTPResponse(statusCode int, contentLength int64) *Trace
- func (t *Trace) AddJSON(payload json.RawMessage) *Trace
- func (t *Trace) AddKubernetesInfo(podName, namespace string) *Trace
- func (t *Trace) AddLink(spanContext SpanContext) *Trace
- func (t *Trace) AddMemoryInfo() *Trace
- func (t *Trace) AddNetworkInfo(protocol string, latency time.Duration) *Trace
- func (t *Trace) AddProcessInfo() *Trace
- func (t *Trace) AddSystemInfo(hostname, ipAddress, environment string) *Trace
- func (t *Trace) AddTaskInfo(taskID, taskName string, retries int) *Trace
- func (t *Trace) AddUser(userID, username string) *Trace
- func (t *Trace) Client() *Trace
- func (t *Trace) Consumer() *Trace
- func (t *Trace) End()
- func (t *Trace) ExtractGRPCContext(ctx context.Context) context.Context
- func (t *Trace) ExtractHTTPContext(req *http.Request) *Trace
- func (t *Trace) GetContext() context.Context
- func (t *Trace) GetParentID() string
- func (t *Trace) GetTraceID() string
- func (t *Trace) InjectGRPCContext(ctx context.Context) context.Context
- func (t *Trace) InjectHTTPContext(req *http.Request) *Trace
- func (t *Trace) Producer() *Trace
- func (t *Trace) RecordError(err error)
- func (t *Trace) RecordFailure(err error, message string)
- func (t *Trace) Server() *Trace
- func (t *Trace) SetStatus(code codes.Code, message string)
- func (t *Trace) SetSuccess(message string)
- func (t *Trace) Start(name string) *Trace
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Init ¶
func Init(ctx context.Context, serviceName string, opts ...InitOption) (context.Context, func(context.Context), error)
Init initializes OpenTelemetry with optional tracing and metrics. It returns the initialized context, a shutdown function, and any encountered error. You can enable metrics by using the `WithMetrics` option, and customize the behavior with additional options.
Parameters: - ctx: A context that will be used by OpenTelemetry for trace and metric collection. - serviceName: The name of the service, used to identify the service in tracing systems. - opts: Variadic options that allow configuring tracing, metrics, exporters, etc.
Returns: - A context enriched with tracing capabilities, a shutdown function to clean up resources, and any encountered error.
Example usage:
ctx, shutdown, err := traceflow.Init(ctx, "my-service", traceflow.WithOLTP("http://otel:4317")) if err != nil { log.Fatalf("Failed to initialize OpenTelemetry: %v", err) } defer shutdown(ctx) // Ensure graceful shutdown of the tracing system // Your application logic goes here // Clean up OpenTelemetry before exiting
func UnaryClientInterceptor ¶
func UnaryClientInterceptor(trace *Trace) grpc.UnaryClientInterceptor
UnaryClientInterceptor is a gRPC client interceptor that injects the trace context into outgoing gRPC requests. This allows the gRPC client to propagate the trace context to downstream services, ensuring that traces can be linked across distributed services.
The interceptor intercepts every gRPC client call, extracts the current trace context from the client's context, and injects it into the outgoing gRPC metadata. This is essential for maintaining end-to-end visibility in distributed systems, allowing the trace to continue across multiple service boundaries.
Example usage:
opts := []grpc.DialOption{ grpc.WithUnaryInterceptor(traceflow.UnaryClientInterceptor()), } conn, err := grpc.Dial("localhost:50051", opts...) if err != nil { log.Fatalf("Failed to connect: %v", err) } defer conn.Close() client := pb.NewMyServiceClient(conn) // Now all outgoing requests will have trace context injected
Notes:
- This interceptor is designed for unary RPCs. For streaming RPCs, a different interceptor (e.g., `StreamClientInterceptor`) is required.
- The trace context is injected using OpenTelemetry's propagator, and the trace context is transmitted in a format that follows the W3C Trace Context standard.
- This interceptor should be included as part of the gRPC client options.
Returns:
- A gRPC `grpc.UnaryClientInterceptor` function that can be added to the gRPC client configuration to enable automatic trace context propagation.
Types ¶
type Attribute ¶
type Attribute struct {
// contains filtered or unexported fields
}
Attribute wraps OpenTelemetry's KeyValue type
func AddBoolSlice ¶
AddBoolSlice creates a bool slice OTEL attribute.
func AddFloatSlice ¶
AddFloatSlice creates a float64 slice OTEL attribute.
func AddIntSlice ¶
AddIntSlice creates an int slice OTEL attribute.
func AddStringSlice ¶
AddStringSlice creates a string slice OTEL attribute.
type InitOption ¶
type InitOption func(*TelemetryBuilder)
InitOption defines a functional option for customizing the Init process
func WithBatchTimeout ¶
func WithBatchTimeout(timeout time.Duration) InitOption
WithBatchTimeout allows users to specify a custom batch timeout for the BatchSpanProcessor.
func WithFileLogging ¶
func WithFileLogging(filePath string) InitOption
WithFileLogging sets up a file exporter to write trace logs to a file.
func WithLogger ¶
func WithLogger(logger *log.Logger) InitOption
WithLogger allows users to provide a custom logger.
func WithMetrics ¶
func WithMetrics() InitOption
WithMetrics enables metric collection and sets up the metric exporter.
func WithOLTP ¶
func WithOLTP(target string) InitOption
WithOLTP sets the OLTP exporter to send traces to an OpenTelemetry collector.
func WithSilentLogger ¶
func WithSilentLogger() InitOption
WithSilentLogger sets a no-op logger and no-op span exporter, useful for testing.
type Option ¶
type Option func(*Trace)
Option defines a function signature for modifying the Trace object
func WithAttributes ¶
WithAttributes allows users to provide custom attributes to be added during the Trace object initialization. WithAttributes allows users to provide custom attributes to be added during the Trace object initialization.
func WithConcurrencyInfo ¶
func WithConcurrencyInfo() Option
WithConcurrencyInfo adds the number of goroutines to the Trace attributes
func WithEnVars ¶
WithEnVars retrieves environment variables specified in the keys slice and adds them as attributes to the Trace. If an environment variable is not set or is empty, a warning is logged, and that attribute is not added.
Example usage:
envKeys := []string{"SERVICE_NAME", "DEPLOYMENT_ENV", "CLOUD_REGION", "SERVICE_VERSION"} trace := traceflow.New(ctx, "my-service", traceflow.WithEnVars(envKeys))
Notes: - Only environment variables that are set and non-empty are added to the trace.
func WithHTTPContext ¶ added in v1.0.0
func WithSystemInfo ¶
func WithSystemInfo() Option
WithSystemInfo adds system-related attributes: CPU, Memory, Disk
type SpanContext ¶
type SpanContext struct {
// contains filtered or unexported fields
}
SpanContext wraps the OpenTelemetry span context type.
func NewSpanContext ¶
func NewSpanContext(sc trace.SpanContext) SpanContext
NewSpanContext creates a new SpanContext from OpenTelemetry's span context.
type SpanKind ¶
type SpanKind struct {
// contains filtered or unexported fields
}
SpanKind allows fluent setting of the span kind.
type TelemetryBuilder ¶
type TelemetryBuilder struct {
// contains filtered or unexported fields
}
TelemetryBuilder holds configuration for OTEL setup
type Trace ¶
type Trace struct {
// contains filtered or unexported fields
}
Trace is a struct that holds the context, tracer, span, and attributes for a trace
func New ¶
New creates a new Trace object using the specified tracer from the OpenTelemetry provider. If context is nil, a valid context is created for the trace. This context is used for trace propagation and management. Users can pass variadic options to customize the trace, including automatically adding system-related attributes, custom attributes, or any other predefined behaviors.
New also automatically propagates the trace context from the provided context. This ensures that the trace is linked to any existing parent trace. If no trace exists in the provided context, it starts a fresh trace.
Example usage:
// Create a new Trace with default settings trace := traceflow.New(ctx, "my-service") // Create a new Trace with system information trace := traceflow.New(ctx, "my-service", traceflow.WithSystemInfo()) // Create a new Trace with custom attributes trace := traceflow.New(ctx, "my-service", traceflow.WithAttributes( attribute.String("user_id", "123"), attribute.Int("request_count", 5), ))
Notes: - The options allow flexibility in configuring the Trace object during initialization. - You can create multiple options to fit various use cases and simplify tracing setup.
func NewWithoutPropagation ¶
NewWithoutPropagation creates a new Trace object without propagating the trace context from the provided context. This treats the current trace as a parent, but does not copy the context. Use this method when you want the new trace to start independently.
Example usage:
// Create a new trace without propagating the existing context trace := traceflow.NewWithoutPropagation(ctx, "my-service") // The new trace will not be linked to the parent trace.
func (*Trace) AddAttribute ¶
AddAttribute appends one or more OpenTelemetry attributes to the current trace. This method accepts variadic attribute.KeyValue arguments, allowing the caller to add single or multiple attributes in a single call. It supports both OpenTelemetry predefined attributes (e.g., String, Int, Bool) and custom attributes formatted as attribute.KeyValue objects.
Example usage:
// Add a single attribute trace.AddAttribute(attribute.String("user_id", "123")) // Add multiple attributes trace.AddAttribute( attribute.String("user_id", "123"), attribute.Int("http_status", 200), attribute.Bool("success", true), )
AddAttribute accepts one or more custom TraceFlow attributes and appends them to the trace.
func (*Trace) AddAttributeIf ¶
AddAttributeIf conditionally adds an attribute to the trace based on a boolean condition. If the condition (cond) is true, the attribute specified by the key and value is added to the trace. The method automatically determines the correct OpenTelemetry attribute type (e.g., string, int, float, bool) based on the value provided.
Supported types for the value parameter include: - string - int, int32, int64 - uint, uint32, uint64 - float32, float64 - bool
If the value is of an unsupported type, the attribute is not added.
Example usage:
// Conditionally add an attribute only if the user ID is valid trace.AddAttributeIf(isValidUser, "user_id", "12345") // Conditionally add a numeric attribute trace.AddAttributeIf(isSuccess, "response_time", 150)
This method is particularly useful when attributes should only be included in the trace under specific conditions (e.g., based on business logic or performance metrics).
If the condition is false, no attribute is added, and the trace remains unchanged.
func (*Trace) AddCPUInfo ¶
AddCPUInfo adds CPU count and CPU architecture attributes to the trace. This information is gathered automatically using Go's runtime package.
Example usage:
trace.AddCpuInfo()
func (*Trace) AddContainerInfo ¶
AddContainerInfo automatically adds container-related attributes such as the container ID and the image to the trace. The container ID is retrieved from the cgroup file, and the container image is fetched from the CONTAINER_IMAGE environment variable.
Attributes added: - container.id: The container ID, retrieved from the cgroup file. - container.image: The container image, retrieved from the environment or set to "unknown".
Example usage:
trace.AddContainerInfo()
Notes: - This method is designed to work in Docker or Kubernetes environments.
func (*Trace) AddCustomMetric ¶
AddCustomMetric adds a custom metric to the trace.
func (*Trace) AddDBColumnInfo ¶
AddDBColumnInfo adds database column-related attributes like column name and column count.
func (*Trace) AddDBConnectionInfo ¶
AddDBConnectionInfo adds database connection-related attributes like connection string and connection count.
func (*Trace) AddDBErrorInfo ¶
AddDBErrorInfo adds database error-related attributes like error message and error code.
func (*Trace) AddDBIndexInfo ¶
AddDBIndexInfo adds database index-related attributes like index name and index count.
func (*Trace) AddDBInfo ¶
AddDBInfo adds database-related attributes like database name and version.
func (*Trace) AddDBQuery ¶
AddDBQuery adds database query information to the trace.
func (*Trace) AddDBTableInfo ¶
AddDBTableInfo adds database table-related attributes like table name and row count.
func (*Trace) AddDBTransactionInfo ¶
AddDBTransactionInfo adds database transaction-related attributes like transaction ID and status.
func (*Trace) AddDiskInfo ¶
AddDiskInfo automatically adds disk-related attributes to the trace. This includes details such as total disk space and free disk space. The information is retrieved using system calls to gather disk statistics.
Attributes added: - disk.total: Total disk space in bytes. - disk.free: Free disk space in bytes.
Example usage:
trace.AddDiskInfo()
Notes:
- Disk statistics are collected automatically for the root filesystem ("/").
- This implementation uses syscall for Unix-like systems. Adjustments may be required for other operating systems.
func (*Trace) AddException ¶
AddException adds exception information to the trace.
func (*Trace) AddHTTPHeaders ¶
AddHTTPHeaders adds HTTP headers as attributes to the trace.
func (*Trace) AddHTTPRequest ¶
AddHTTPRequest adds HTTP request details as attributes to the trace.
func (*Trace) AddHTTPResponse ¶
AddHTTPResponse adds HTTP response details as attributes to the trace.
func (*Trace) AddJSON ¶
func (t *Trace) AddJSON(payload json.RawMessage) *Trace
AddJSON adds a JSON payload as a string attribute to the trace. The JSON payload is passed as a json.RawMessage, which is then converted to a string and added to the trace as an OpenTelemetry string attribute with the key "payload". This method is useful when you want to include JSON-encoded data as part of the trace's attributes.
Example usage:
jsonPayload := json.RawMessage(`{"key":"value"}`) trace.AddJSON(jsonPayload)
The resulting trace attribute will include the JSON data as a string:
"payload": "{\"key\":\"value\"}"
This method is particularly useful when you need to include structured data (such as API responses or request bodies) in your traces, but want to store it as a single string attribute.
Note that the JSON data is not parsed or validated, and is added directly as a string. Be mindful of the size of the JSON payload, as OpenTelemetry attributes have practical size limits that should not be exceeded.
func (*Trace) AddKubernetesInfo ¶
AddKubernetesInfo adds Kubernetes-related attributes like pod name and namespace.
func (*Trace) AddLink ¶
func (t *Trace) AddLink(spanContext SpanContext) *Trace
AddLink adds a link to another span within the current traceflow span. Span links are used to connect spans that are related but do not have a direct parent-child relationship. This is useful when spans from different traces or parts of the same trace are logically related and should be connected.
The linked span can come from either the same trace or a different trace. The link helps trace analyzers understand the relationships between otherwise unrelated spans and allows them to be visualized as part of a larger operation.
Example usage:
// Link another span's context to the current span otherSpanContext := traceflow.NewSpanContext(externalOtelSpanContext) trace.AddLink(otherSpanContext)
This method is particularly useful in scenarios like batch processing, where a single span may be related to multiple spans that are processed together, but do not have direct hierarchical relationships.
Notes:
- The linked span is represented by its traceflow.SpanContext, which wraps the OpenTelemetry span context (trace.SpanContext).
- This method returns the Trace object, allowing chaining of additional methods.
- Users interact with traceflow's custom SpanContext type to avoid the need to directly import or use OpenTelemetry types, making tracing integration easier.
func (*Trace) AddMemoryInfo ¶
AddMemoryInfo automatically adds memory-related attributes to the trace. This includes details such as total memory allocation, system memory, and heap memory. The memory information is retrieved using Go's runtime package.
Attributes added: - memory.total_alloc: Total bytes allocated. - memory.sys: System memory in use. - memory.heap_alloc: Heap memory allocated. - memory.heap_idle: Heap memory currently idle.
Example usage:
trace.AddMemoryInfo()
Notes: - The memory statistics are collected automatically, and no manual input is required.
func (*Trace) AddNetworkInfo ¶
AddNetworkInfo adds network-related attributes to the trace.
func (*Trace) AddProcessInfo ¶
AddProcessInfo automatically adds process-related attributes such as the process ID and the command being executed to the trace. The process ID is retrieved using Go's os package, and the command is determined from the current executable.
Attributes added: - process.id: The current process ID. - process.command: The command or path of the executable.
Example usage:
trace.AddProcessInfo()
Notes: - If the command cannot be determined, it defaults to "unknown".
func (*Trace) AddSystemInfo ¶
AddSystemInfo adds system-related attributes like hostname and environment.
func (*Trace) AddTaskInfo ¶
AddTaskInfo adds task-related information to the trace.
func (*Trace) Client ¶
Client sets the span kind to client and returns the Trace object for chaining.
func (*Trace) Consumer ¶
Consumer sets the span kind to consumer and returns the Trace object for chaining.
func (*Trace) End ¶
func (t *Trace) End()
End marks the completion of the current span, signaling the end of the operation being traced. This method should be called after the span's operation has completed, allowing the trace to accurately record the duration and any final status or attributes of the span.
Example usage:
// Start a span trace.Start("operation") // Perform some operations... // End the span once the operation is complete trace.End()
Best Practices:
// Ensure that the span is always ended, even in the case of errors, by using defer: defer trace.Start("operation").End()
The End method is a critical part of the span lifecycle, as it ensures the span is properly closed and its data is recorded in the trace. If the span is nil, the method is a no-op, meaning it will do nothing.
Notes:
- It is important to ensure that spans are always ended, either explicitly or using defer to guarantee they are closed, even in the case of errors.
- Once a span has ended, no additional attributes or status can be set on it.
func (*Trace) ExtractGRPCContext ¶
ExtractGRPCContext extracts the trace context from gRPC metadata. This is useful in a gRPC server to continue a trace initiated by an upstream service, ensuring that the trace context flows through the distributed system as part of the service request lifecycle.
This method uses OpenTelemetry's propagator to extract the trace context from gRPC metadata present in the incoming request. The extracted trace context is then used to update the current Trace's context (t.ctx), allowing the service to join the existing trace and continue the tracing process.
Example usage:
func (s *server) SomeRPC(ctx context.Context, req *pb.Request) (*pb.Response, error) { trace := traceflow.New(ctx, "grpc-server") // Extract trace context from incoming gRPC request trace.ExtractGRPCContext(ctx) // Continue the trace defer trace.Start("processing-request").End() // Handle request return &pb.Response{}, nil }
This method is particularly useful in distributed architectures where services need to propagate trace context with each request to maintain full trace visibility.
Notes:
- The trace context is expected to be present in the incoming gRPC metadata in a format compatible with OpenTelemetry's propagation standards (W3C Trace Context by default).
- If no metadata is found in the context, or the trace context is missing, the method returns the original context unmodified.
func (*Trace) ExtractHTTPContext ¶
ExtractHTTPContext extracts the trace context from the headers of an HTTP request and updates the Trace's context. This ensures that the current service can join an existing trace initiated by an upstream service.
The trace context is extracted using the global propagator. Users of traceflow do not need to interact with OpenTelemetry’s propagators directly.
Example usage:
trace := traceflow.New(ctx, "my-service") trace.ExtractHTTPContext(req)
Notes: - This method updates the Trace's context (t.ctx) with the extracted trace context.
func (*Trace) GetContext ¶
GetContext returns the context associated with the current span. The context carries metadata, including trace and span information, which is used for trace propagation across service boundaries.
Example usage:
ctx := trace.GetContext() // Use the context in subsequent operations
This method is particularly useful when you need to pass the context to downstream services or operations that require trace propagation.
Notes:
- Ensure that the context is valid and has been properly initialized before passing it to other functions or services.
func (*Trace) GetParentID ¶
GetParentID returns the parent span ID of the current trace, if it exists. This ID represents the span from which the current span is derived, allowing the trace to establish relationships between parent and child spans.
If the parent span ID is available, it is returned as a string. If no parent span exists, an empty string is returned.
Example usage:
parentID := trace.GetParentID() fmt.Println("Parent Span ID:", parentID)
Notes:
- The parent span ID is important for understanding the hierarchy of spans within a distributed trace.
func (*Trace) GetTraceID ¶
GetTraceID returns the unique trace ID of the current span. The trace ID is part of the span's context and is used to identify the trace in a distributed system.
If the span's context is valid, the trace ID is returned as a string. Otherwise, an empty string is returned.
Example usage:
traceID := trace.GetTraceID() fmt.Println("Current Trace ID:", traceID)
Notes:
- The trace ID is useful for tracking and correlating traces across multiple services in distributed systems.
func (*Trace) InjectGRPCContext ¶
InjectGRPCContext injects the trace context into the gRPC metadata. This is useful for propagating trace information across gRPC service boundaries. The trace context allows downstream services to continue the trace, providing full visibility into the flow of operations in a distributed system.
This method uses OpenTelemetry's propagator to inject the trace context into gRPC metadata, ensuring that trace information is propagated with outgoing gRPC requests.
After injection, the trace context is stored in the gRPC metadata and appended to the outgoing context, which will be used in the gRPC client to send the trace context along with the request.
Example usage:
// Create a new trace in the gRPC client trace := traceflow.New(ctx, "grpc-client") // Inject the trace context into the outgoing gRPC request ctx = trace.InjectGRPCContext(ctx) // Perform a gRPC call with the injected trace context response, err := client.SomeRPC(ctx, &pb.Request{}) if err != nil { log.Fatalf("Failed to call gRPC service: %v", err) } // Continue trace logic if needed trace.Start("some-operation").End()
Notes:
- This method should be used in the gRPC client to propagate trace context to downstream services.
- The trace context is appended to the context as gRPC metadata, using the W3C Trace Context format by default.
- If the trace context (`t.ctx`) is nil or not properly initialized, this method is a no-op and does not modify the outgoing context.
func (*Trace) InjectHTTPContext ¶
InjectHTTPContext injects the trace context into the headers of an HTTP request. This ensures that the context of a trace is propagated across service boundaries in distributed systems.
The trace context is injected using the global propagator, which handles the serialization of the trace context as HTTP headers. Users of traceflow do not need to import or manage OpenTelemetry propagators directly.
Example usage:
req, _ := http.NewRequest("GET", "http://example.com", nil) trace.InjectHTTPContext(req)
Notes:
- The trace context is injected into the HTTP request's headers using the default W3C Trace Context format.
func (*Trace) Producer ¶
Producer sets the span kind to producer and returns the Trace object for chaining.
func (*Trace) RecordError ¶
RecordError records an error to the span and sets the span status to Error.
func (*Trace) RecordFailure ¶
RecordFailure records an error to the current span and marks the span's status as Error with a custom message. This method is useful for handling failure scenarios where both the error itself and a custom message need to be captured in the trace.
The error is recorded using the RecordError method, and the span's status is set to codes.Error to reflect that the span represents a failed operation. A custom message is also provided to give additional context on the nature of the failure.
Example usage:
// Record a failure in the span with an error and a custom message trace.RecordFailure(err, "failed to process user request")
This method is a convenient way to handle both error reporting and span status setting in failure cases, ensuring that the trace contains both the error details and the status information.
Notes:
- Ensure the span is properly started before recording failures.
- The recorded error and message will be part of the trace and can be viewed in trace analysis tools for debugging and diagnostics.
func (*Trace) Server ¶
Server sets the span kind to server and returns the Trace object for chaining.
func (*Trace) SetStatus ¶
SetStatus sets the status of the current span with a custom code and message. This is useful for recording the outcome of the operation represented by the span, providing context on whether the operation succeeded, failed, or encountered an error.
The status code should be chosen from OpenTelemetry's predefined status codes (codes.Code), which include options like: - codes.Ok (indicating success) - codes.Error (indicating failure)
The message should provide additional context or details about the status.
Example usage:
// Set the span's status to indicate an error trace.SetStatus(codes.Error, "database connection failed")
Notes: - Ensure the span is properly started before setting its status. - This method allows the trace to capture both the status code and a descriptive message.
func (*Trace) SetSuccess ¶
SetSuccess marks the current span as successful by setting its status to codes.Ok, along with a custom success message. This is useful for marking the span as completed without any errors and providing a message that reflects the success.
Example usage:
// Mark the span as successful with a custom message trace.SetSuccess("operation completed successfully")
This method is a shorthand for calling SetStatus with codes.Ok, simplifying the process of marking successful spans. It is particularly useful when you want to standardize how success is recorded in your traces.
func (*Trace) Start ¶
Start creates a new span within the existing trace using the provided name. It includes any attributes, links, and options that have been set on the trace. After the span is created, attributes, links, and options are cleared to avoid accidental reuse in future spans.
If a span kind (e.g., server, client) has been set, it will also be applied to the span during creation.
Example usage:
trace := traceflow.New(ctx, "my-service") defer trace.Start("operation_name").End()
Notes: - This method formats the operation name as "<service>.<name>". - Once a span is started, it must be ended using the End method.