traceflow

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2024 License: MIT Imports: 29 Imported by: 0

Documentation

Overview

Package traceflow provides a simple wrapper around OpenTelemetry to make it easier to create and manage traces.

Index

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 AddBool

func AddBool(key string, value bool) Attribute

AddBool creates a bool OTEL attribute.

func AddBoolSlice

func AddBoolSlice(key string, value []bool) Attribute

AddBoolSlice creates a bool slice OTEL attribute.

func AddFloat

func AddFloat(key string, value float64) Attribute

AddFloat creates an int64 OTEL attribute.

func AddFloatSlice

func AddFloatSlice(key string, value []float64) Attribute

AddFloatSlice creates a float64 slice OTEL attribute.

func AddInt

func AddInt(key string, value int) Attribute

AddInt creates an int OTEL attribute.

func AddIntSlice

func AddIntSlice(key string, value []int) Attribute

AddIntSlice creates an int slice OTEL attribute.

func AddString

func AddString(key, value string) Attribute

AddString creates a string OTEL attribute.

func AddStringSlice

func AddStringSlice(key string, value []string) Attribute

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

func WithAttributes(attrs ...Attribute) Option

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

func WithEnVars(keys []string) Option

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 WithHTTPContext(req *http.Request) Option

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

func New(ctx context.Context, spanName string, opts ...Option) *Trace

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

func NewWithoutPropagation(ctx context.Context, spanName string, opts ...Option) *Trace

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 Now added in v1.0.0

func Now(ctx context.Context, name, operation string, opts ...Option) *Trace

Now creates and starts a trace with options immediately.

func (*Trace) AddAttribute

func (t *Trace) AddAttribute(attrs ...Attribute) *Trace

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

func (t *Trace) AddAttributeIf(cond bool, key string, value interface{}) *Trace

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

func (t *Trace) AddCPUInfo() *Trace

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

func (t *Trace) AddContainerInfo() *Trace

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

func (t *Trace) AddCustomMetric(metricName string, value float64) *Trace

AddCustomMetric adds a custom metric to the trace.

func (*Trace) AddDBColumnInfo

func (t *Trace) AddDBColumnInfo(columnName string, columnCount int) *Trace

AddDBColumnInfo adds database column-related attributes like column name and column count.

func (*Trace) AddDBConnectionInfo

func (t *Trace) AddDBConnectionInfo(connectionString string, connectionCount int) *Trace

AddDBConnectionInfo adds database connection-related attributes like connection string and connection count.

func (*Trace) AddDBErrorInfo

func (t *Trace) AddDBErrorInfo(errorMessage, errorCode string) *Trace

AddDBErrorInfo adds database error-related attributes like error message and error code.

func (*Trace) AddDBIndexInfo

func (t *Trace) AddDBIndexInfo(indexName string, indexCount int) *Trace

AddDBIndexInfo adds database index-related attributes like index name and index count.

func (*Trace) AddDBInfo

func (t *Trace) AddDBInfo(dbName, dbVersion string) *Trace

AddDBInfo adds database-related attributes like database name and version.

func (*Trace) AddDBQuery

func (t *Trace) AddDBQuery(query, dbType string) *Trace

AddDBQuery adds database query information to the trace.

func (*Trace) AddDBTableInfo

func (t *Trace) AddDBTableInfo(tableName string, rowCount int) *Trace

AddDBTableInfo adds database table-related attributes like table name and row count.

func (*Trace) AddDBTransactionInfo

func (t *Trace) AddDBTransactionInfo(transactionID, status string) *Trace

AddDBTransactionInfo adds database transaction-related attributes like transaction ID and status.

func (*Trace) AddDiskInfo

func (t *Trace) AddDiskInfo() *Trace

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) AddError

func (t *Trace) AddError(err error) *Trace

AddError adds error information to the trace.

func (*Trace) AddEvent

func (t *Trace) AddEvent(eventName string, timestamp time.Time) *Trace

AddEvent adds an event name and timestamp as an attribute to the trace.

func (*Trace) AddException

func (t *Trace) AddException(err error, stackTrace string) *Trace

AddException adds exception information to the trace.

func (*Trace) AddHTTPHeaders

func (t *Trace) AddHTTPHeaders(headers http.Header) *Trace

AddHTTPHeaders adds HTTP headers as attributes to the trace.

func (*Trace) AddHTTPRequest

func (t *Trace) AddHTTPRequest(req *http.Request) *Trace

AddHTTPRequest adds HTTP request details as attributes to the trace.

func (*Trace) AddHTTPResponse

func (t *Trace) AddHTTPResponse(statusCode int, contentLength int64) *Trace

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

func (t *Trace) AddKubernetesInfo(podName, namespace string) *Trace

AddKubernetesInfo adds Kubernetes-related attributes like pod name and namespace.

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

func (t *Trace) AddMemoryInfo() *Trace

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

func (t *Trace) AddNetworkInfo(protocol string, latency time.Duration) *Trace

AddNetworkInfo adds network-related attributes to the trace.

func (*Trace) AddProcessInfo

func (t *Trace) AddProcessInfo() *Trace

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

func (t *Trace) AddSystemInfo(hostname, ipAddress, environment string) *Trace

AddSystemInfo adds system-related attributes like hostname and environment.

func (*Trace) AddTaskInfo

func (t *Trace) AddTaskInfo(taskID, taskName string, retries int) *Trace

AddTaskInfo adds task-related information to the trace.

func (*Trace) AddUser

func (t *Trace) AddUser(userID, username string) *Trace

AddUser adds user-related attributes to the trace.

func (*Trace) Client

func (t *Trace) Client() *Trace

Client sets the span kind to client and returns the Trace object for chaining.

func (*Trace) Consumer

func (t *Trace) Consumer() *Trace

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

func (t *Trace) ExtractGRPCContext(ctx context.Context) context.Context

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

func (t *Trace) ExtractHTTPContext(req *http.Request) *Trace

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

func (t *Trace) GetContext() context.Context

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

func (t *Trace) GetParentID() string

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

func (t *Trace) GetTraceID() string

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

func (t *Trace) InjectGRPCContext(ctx context.Context) context.Context

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

func (t *Trace) InjectHTTPContext(req *http.Request) *Trace

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

func (t *Trace) Producer() *Trace

Producer sets the span kind to producer and returns the Trace object for chaining.

func (*Trace) RecordError

func (t *Trace) RecordError(err error)

RecordError records an error to the span and sets the span status to Error.

func (*Trace) RecordFailure

func (t *Trace) RecordFailure(err error, message string)

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

func (t *Trace) Server() *Trace

Server sets the span kind to server and returns the Trace object for chaining.

func (*Trace) SetStatus

func (t *Trace) SetStatus(code codes.Code, message string)

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

func (t *Trace) SetSuccess(message string)

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

func (t *Trace) Start(name string) *Trace

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.

Directories

Path Synopsis
internal
errors
Package errors is a custom package that holds error definitions for traceflow.
Package errors is a custom package that holds error definitions for traceflow.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL