instana

package module
v1.62.1 Latest Latest
Warning

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

Go to latest
Published: Apr 23, 2024 License: MIT Imports: 42 Imported by: 78

README

IBM Instana Go Tracer

Build Status PkgGoDev OpenTracing Go Report Card

The IBM Instana Go Tracer is an SDK that collects traces, metrics, logs and provides profiling for Go applications. The tracer is part of the IBM Instana Observability tool set.

Compatibility

Tracer Version Go version
v1.62.0 and higher v1.21.0 and higher
v1.47.0 to v1.61.0 v1.13.0 and higher
Less than v1.47.0 v1.9.0 and higher

[!NOTE] Make sure to always use the latest version of the tracer, as it provides new features, improvements, security updates and fixes.

[!IMPORTANT] Since v1.53.0, the Go Tracer uses fsm v1.0.1 internally. Customers using fsm prior to v1 in their projects will need to update it to v1.

Installation

To add the tracer to your project, run:

go get -u github.com/instana/go-sensor@latest

[!NOTE] As a good practice, add this command to your CI pipeline or your automated tool before building the application to keep the tracer up to date.

Usage

Initial Setup

Once the tracer is added to the project, import the package into the entrypoint file of your application:

import (
  ...
  instana "github.com/instana/go-sensor"
)

Create a reference to the collector and initialize it with a service name:

var (
  ...
  col instana.TracerLogger
)

func init() {
  ...
  col = instana.InitCollector(&instana.Options{
    Service: "My app",
  })
}

[!NOTE] The tracer expects the Instana Agent to be up and running in the default port 42699. You can change the port with the environment variable INSTANA_AGENT_PORT.

[!NOTE] For non default options, like the Agent host and port, the tracer can be configured either via SDK options, environment variables or Agent options.

Collecting Metrics

Once the collector has been initialized with instana.InitCollector, application metrics such as memory, CPU consumption, active goroutine count etc will be automatically collected and reported to the Agent without further actions or configurations to the SDK. This data is then already available in the dashboard.

Tracing Calls

Let's collect traces of calls received by an HTTP server.

Before any changes, your code should look something like this:

// endpointHandler is the standard http.Handler function
http.HandleFunc("/endpoint", endpointHandler)

log.Fatal(http.ListenAndServe(":9090", nil))

Wrap the endpointHandler function with instana.TracingHandlerFunc. Now your code should look like this:

// endpointHandler is now wrapped by `instana.TracingHandlerFunc`
http.HandleFunc("/endpoint", instana.TracingHandlerFunc(col, "/endpoint", endpointHandler))

log.Fatal(http.ListenAndServe(":9090", nil))

When running the application, every time /endpoint is called, the tracer will collect this data and send it to the Instana Agent. You can monitor traces to this endpoint in the Instana UI.

Profiling

Unlike metrics, profiling needs to be enabled with the EnableAutoProfile option, as seen here:

col = instana.InitCollector(&instana.Options{
  Service: "My app",
  EnableAutoProfile: true,
})

You should be able to see your application profiling in the Instana UI under Analytics/Profiles.

Logging

In terms of logging, the SDK provides two distinct logging features:

  1. Traditional logging, that is, logs reported to the standard output, usually used for debugging purposes
  2. Instana logs, a feature that allows customers to report logs to the dashboard under Analytics/Logs
Traditional Logging

Many logs are provided by the SDK, usually prefixed with "INSTANA" and are useful to understand what the tracer is doing underneath. It can also be used for debugging and troubleshoot reasons. Customers can also provide logs by calling one of the following: Collector.Info(), Collector.Warn(), Collector.Error(), Collector.Debug(). You can setup the log level via options or the INSTANA_LOG_LEVEL environment variable.

You can find detailed information in the Instana documentation.

Instana Logs

Instana Logs are spans of the type log.go that are rendered in a special format in the dashboard. You can create logs and report them to the agent or attach them as children of an existing span.

The code snippet below shows how to create logs and send them to the agent:

col := instana.InitCollector(&instana.Options{
  Service: "My Go App",
})

col.StartSpan("log.go", []ot.StartSpanOption{
  ot.Tags{
    "log.level":   "error", // available levels: info, warn, error, debug
    "log.message": "error from log.go span",
  },
}...).Finish() // make sure to "finish" the span, so it's sent to the agent

This log can then be visualized in the dashboard under Analytics/Logs. You can add a filter by service name. In our example, the service name is "My Go App".

Opt-in Exit Spans

Go tracer support the opt-in feature for the exit spans. When enabled, the collector can start capturing exit spans, even without an entry span. This capability is particularly useful for scenarios like cronjobs and other background tasks, enabling the users to tailor the tracing according to their specific requirements. By setting the INSTANA_ALLOW_ROOT_EXIT_SPAN variable, users can choose whether the tracer should start a trace with an exit span or not. The environment variable can have 2 values. (1: Tracer should record exit spans for the outgoing calls, when it has no active entry span. 0 or any other values: Tracer should not start a trace with an exit span).

export INSTANA_ALLOW_ROOT_EXIT_SPAN=1
Complete Example

Basic Usage

package main

import (
  "log"
  "net/http"

  instana "github.com/instana/go-sensor"
)

func main() {
  col := instana.InitCollector(&instana.Options{
    Service:           "Basic Usage",
    EnableAutoProfile: true,
  })

  http.HandleFunc("/endpoint", instana.TracingHandlerFunc(col, "/endpoint", func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
  }))

  log.Fatal(http.ListenAndServe(":7070", nil))
}
Wrapping up

Let's quickly summarize what we have seen so far:

  1. We learned how to install, import and initialize the Instana Go Tracer.
  2. Once the tracer is initialized, application metrics are collected out of the box.
  3. Application profiling can be enabled via the EnableAutoProfile option.
  4. Tracing incoming HTTP requests by wrapping the Go standard library http.Handler with instana.TracingHandlerFunc.

With this knowledge it's already possible to make your Go application traceable by our SDK. But there is much more you can do to enhance tracing for your application.

The basic functionality covers tracing for the following standard Go features:

  1. HTTP incoming requests
  2. HTTP outgoing requests
  3. SQL drivers

As we already covered HTTP incoming requests, we suggest that you understand how to collect data from HTTP outgoing requests and SQL driver databases.

Another interesting feature is the usage of additional packages located under instrumentation. Each of these packages provide tracing for specific Go packages like the AWS SDK, Gorm and Fiber.

What's Next

  1. Tracer Options
  2. Tracing HTTP Outgoing Requests
  3. Tracing SQL Driver Databases
  4. Tracing Other Go Packages
  5. Instrumenting Code Manually

Documentation

Overview

Example (CollectorBasicUsage)
package main

import (
	"time"

	instana "github.com/instana/go-sensor"
)

func main() {
	// Initialize the collector
	c := instana.InitCollector(&instana.Options{
		// If Service is not provided, the executable filename will be used instead.
		// We recommend that Service be set.
		Service: "my-go-app",
	})

	// Instrument something
	sp := c.StartSpan("my_span")

	time.Sleep(time.Second * 3)

	sp.Finish()
}
Output:

Example (CollectorWithHTTPServer)
package main

import (
	"fmt"
	"net/http"

	instana "github.com/instana/go-sensor"
)

func main() {
	c := instana.InitCollector(&instana.Options{
		Service: "my-go-app",
	})

	handler := func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "Ok")
	}

	http.HandleFunc("/foo", instana.TracingHandlerFunc(c.LegacySensor(), "/foo", handler))
}
Output:

Example (HttpRoutePatternMatching)

This example demonstrates how to instrument a 3rd-party HTTP router that uses pattern matching to make sure the original path template is forwarded to Instana

package main

import (
	"log"
	"net/http"

	instana "github.com/instana/go-sensor"
)

func main() {
	sensor := instana.NewSensor("my-http-server")

	// Initialize your router. Here for simplicity we use stdlib http.ServeMux, however you
	// can use any router that supports http.Handler/http.HandlerFunc, such as github.com/gorilla/mux
	r := http.NewServeMux()

	// Wrap the handler using instana.TracingHandlerFunc() and pass the path template
	// used to route requests to it. This value will be attached to the span and displayed
	// in UI as `http.path_tpl` if the request path is different (we assume that this request
	// has been routed to the handler via a matched pattern)
	r.HandleFunc("/articles/{category}/{id:[0-9]+}", instana.TracingHandlerFunc(
		sensor,
		"/articles/{category}/{id:[0-9]+}",
		func(w http.ResponseWriter, req *http.Request) {
			// ...
		},
	))

	if err := http.ListenAndServe(":0", nil); err != nil {
		log.Fatalf("failed to start server: %s", err)
	}
}
Output:

Example (RoundTripper)

This example shows how to instrument an HTTP client with Instana tracing

package main

import (
	"context"
	"log"
	"net/http"

	instana "github.com/instana/go-sensor"
	"github.com/opentracing/opentracing-go/ext"
)

func main() {
	col := instana.InitCollector(&instana.Options{
		Service: "my-http-client",
	})

	// Wrap the original http.Client transport with instana.RoundTripper().
	// The http.DefaultTransport will be used if there was no transport provided.
	client := &http.Client{
		Transport: instana.RoundTripper(col, nil),
	}

	// Every call should start with an entry span (https://www.ibm.com/docs/en/instana-observability/current?topic=tracing-best-practices#start-new-traces-with-entry-spans)
	// Normally this would be your HTTP/GRPC/message queue request span, but here we need to create it explicitly, since an HTTP client call is
	// an exit span. And all exit spans must have a parent entry span.
	sp := col.Tracer().StartSpan("client-call")
	sp.SetTag(string(ext.SpanKind), "entry")

	req, err := http.NewRequest(http.MethodGet, "https://www.instana.com", nil)
	if err != nil {
		log.Fatalf("failed to create request: %s", err)
	}

	// Inject the parent span into request context
	ctx := instana.ContextWithSpan(context.Background(), sp)

	// Use your instrumented http.Client to propagate tracing context with the request
	_, err = client.Do(req.WithContext(ctx))
	if err != nil {
		log.Fatalf("failed to GET https://www.instana.com: %s", err)
	}

	// Remember to always finish spans that were created manually to make sure it's propagated to the Agent.
	// In this case, we want to make sure that the entry span is finished after the HTTP request is completed.
	// Optionally, we could use defer right after the span is created.
	sp.Finish()
}
Output:

Example (TracingNamedHandlerFunc)

This example shows how to instrument an HTTP server with Instana tracing

sensor := instana.NewSensor("my-http-server")

// To instrument a handler function, pass it as an argument to instana.TracingHandlerFunc()
http.HandleFunc("/", instana.TracingHandlerFunc(sensor, "/", func(w http.ResponseWriter, req *http.Request) {
	// Extract the parent span and use its tracer to initialize any child spans to trace the calls
	// inside the handler, e.g. database queries, 3rd-party API requests, etc.
	if parent, ok := instana.SpanFromContext(req.Context()); ok {
		sp := parent.Tracer().StartSpan("index", opentracing.ChildOf(parent.Context()))
		defer sp.Finish()
	}

	// ...

	w.Write([]byte("OK"))
}))

// In case your handler is implemented as an http.Handler, pass its ServeHTTP method instead.
// You can also use instana.TracingNamedHandlerFunc() to provide a unique route identifier to
// group the calls to this route later in Instana UI.
http.HandleFunc("/files", instana.TracingNamedHandlerFunc(sensor, "index", "/:path", http.FileServer(http.Dir("./")).ServeHTTP))

if err := http.ListenAndServe(":0", nil); err != nil {
	log.Fatalf("failed to start server: %s", err)
}
Output:

Index

Examples

Constants

View Source
const (
	SeverityChange   severity = -1
	SeverityWarning  severity = 5
	SeverityCritical severity = 10
)

Severity values for events sent to the instana agent

View Source
const (
	ServicePlugin = "com.instana.forge.connection.http.logical.LogicalWebApp"
	ServiceHost   = ""
)

Defaults for the Event API

View Source
const (
	Error = 0
	Warn  = 1
	Info  = 2
	Debug = 3
)

Valid log levels

View Source
const (
	// EqualsMatcher matches the string exactly
	EqualsMatcher = "equals"
	// EqualsIgnoreCaseMatcher matches the string exactly ignoring the case
	EqualsIgnoreCaseMatcher = "equals-ignore-case"
	// ContainsMatcher matches the substring in a string
	ContainsMatcher = "contains"
	// ContainsIgnoreCaseMatcher matches the substring in a string ignoring the case
	ContainsIgnoreCaseMatcher = "contains-ignore-case"
	// RegexpMatcher matches the string using a set of regular expressions. Each item in a term list
	// provided to instana.NamedMatcher() must be a valid regular expression that can be compiled using
	// regexp.Compile()
	RegexpMatcher = "regex"
	// NoneMatcher does not match any string
	NoneMatcher = "none"
)
View Source
const (
	// FieldT Trace ID header
	FieldT = "x-instana-t"
	// FieldS Span ID header
	FieldS = "x-instana-s"
	// FieldL Level header
	FieldL = "x-instana-l"
	// FieldB OT Baggage header
	FieldB = "x-instana-b-"
	// FieldSynthetic if set to 1, marks the call as synthetic, e.g.
	// a healthcheck request
	FieldSynthetic = "x-instana-synthetic"
)

Instana header constants

View Source
const (
	// SDK span, a generic span containing arbitrary data. Spans with operation name
	// not listed in the subsequent list will be sent as an SDK spans forwarding all
	// attached tags to the agent
	SDKSpanType = RegisteredSpanType("sdk")
	// HTTP server and client spans
	HTTPServerSpanType = RegisteredSpanType("g.http")
	HTTPClientSpanType = RegisteredSpanType("http")
	// RPC server and client spans
	RPCServerSpanType = RegisteredSpanType("rpc-server")
	RPCClientSpanType = RegisteredSpanType("rpc-client")
	// Kafka consumer/producer span
	KafkaSpanType = RegisteredSpanType("kafka")
	// Google Cloud Storage client span
	GCPStorageSpanType = RegisteredSpanType("gcs")
	// Google Cloud PubSub client span
	GCPPubSubSpanType = RegisteredSpanType("gcps")
	// AWS Lambda entry span
	AWSLambdaEntrySpanType = RegisteredSpanType("aws.lambda.entry")
	// AWS S3 client span
	AWSS3SpanType = RegisteredSpanType("s3")
	// AWS SQS client span
	AWSSQSSpanType = RegisteredSpanType("sqs")
	// AWS SNS client span
	AWSSNSSpanType = RegisteredSpanType("sns")
	// AWS DynamoDB client span
	AWSDynamoDBSpanType = RegisteredSpanType("dynamodb")
	// AWS Lambda invoke span
	AWSLambdaInvokeSpanType = RegisteredSpanType("aws.lambda.invoke")
	// Logging span
	LogSpanType = RegisteredSpanType("log.go")
	// MongoDB client span
	MongoDBSpanType = RegisteredSpanType("mongo")
	// PostgreSQL client span
	PostgreSQLSpanType = RegisteredSpanType("postgres")
	// MySQL client span
	MySQLSpanType = RegisteredSpanType("mysql")
	// Redis client span
	RedisSpanType = RegisteredSpanType("redis")
	// Couchbase client span
	CouchbaseSpanType = RegisteredSpanType("couchbase")
	// Cosmos client span
	CosmosSpanType = RegisteredSpanType("cosmos")
	// RabbitMQ client span
	RabbitMQSpanType = RegisteredSpanType("rabbitmq")
	// Azure function span
	AzureFunctionType = RegisteredSpanType("azf")
	// GraphQL server span
	GraphQLServerType = RegisteredSpanType("graphql.server")
	// GraphQL client span
	GraphQLClientType = RegisteredSpanType("graphql.client")
)

Registered types supported by Instana. The span type is determined based on the operation name passed to the `StartSpan()` call of a tracer.

It is NOT RECOMMENDED to use operation names that match any of these constants in your custom instrumentation code unless you explicitly wish to send data as a registered span. The list of supported tags can be found in the godoc of the respective span tags type below.

View Source
const (
	// DefaultMaxBufferedSpans is the default span buffer size
	DefaultMaxBufferedSpans = 1000
	// DefaultForceSpanSendAt is the default max number of spans to buffer before force sending them to the agent
	DefaultForceSpanSendAt = 500
)
View Source
const (
	// MaxLogsPerSpan The maximum number of logs allowed on a span.
	MaxLogsPerSpan = 2
)
View Source
const (

	// SnapshotPeriod is the amount of time in seconds between snapshot reports.
	SnapshotPeriod = 600
)
View Source
const Version = "1.62.1"

Version is the version of Instana sensor

Variables

View Source
var ErrAgentNotReady = errors.New("agent not ready")

ErrAgentNotReady is an error returned for an attempt to communicate with an agent before the client announcement process is done

Functions

func BatchSize added in v1.10.0

func BatchSize(n int) ot.Tag

BatchSize returns an opentracing.Tag to mark the span as a batched span representing similar span categories. An example of such span would be batch writes to a queue, a database, etc. If the batch size less than 2, then this option has no effect

func ContextWithSpan added in v1.7.0

func ContextWithSpan(ctx context.Context, sp ot.Span) context.Context

ContextWithSpan returns a new context.Context holding a reference to an active span

func EumSnippet deprecated

func EumSnippet(apiKey string, traceID string, meta map[string]string) string

EumSnippet generates javascript code to initialize JavaScript agent

Deprecated: this snippet is outdated and this method will be removed in the next major version. To learn about the way to install Instana EUM snippet please refer to https://docs.instana.io/products/website_monitoring/#installation

func Flush added in v1.36.0

func Flush(ctx context.Context) error

Flush forces Instana collector to send all buffered data to the agent. This method is intended to implement graceful service shutdown and not recommended for intermittent use. Once Flush() is called, it's not guaranteed that collector remains in operational state.

func FormatID added in v1.8.0

func FormatID(id int64) string

FormatID converts an Instana ID to a value that can be used in context propagation (such as HTTP headers). More specifically, this converts a signed 64 bit integer into an unsigned hex string. The resulting string is always padded with 0 to be 16 characters long.

func FormatLongID added in v1.24.0

func FormatLongID(hi, lo int64) string

FormatLongID converts a 128-bit Instana ID passed in two quad words to an unsigned hex string suitable for context propagation.

func Header2ID deprecated

func Header2ID(header string) (int64, error)

Header2ID calls instana.ParseID() and returns its result. This is kept here for backward compatibility with go-sensor@v1.x

Deprecated: please use instana.ParseID() instead

func ID2Header deprecated

func ID2Header(id int64) (string, error)

ID2Header calls instana.FormatID() and returns its result and a nil error. This is kept here for backward compatibility with go-sensor@v1.x

Deprecated: please use instana.FormatID() instead

func InitSensor deprecated

func InitSensor(options *Options)

InitSensor initializes the sensor (without tracing) to begin collecting and reporting metrics.

Deprecated: Use StartMetrics instead.

func InstrumentSQLDriver added in v1.15.0

func InstrumentSQLDriver(sensor TracerLogger, name string, driver driver.Driver)

InstrumentSQLDriver instruments provided database driver for use with `sql.Open()`. This method will ignore any attempt to register the driver with the same name again.

The instrumented version is registered with `_with_instana` suffix, e.g. if `postgres` provided as a name, the instrumented version is registered as `postgres_with_instana`.

func NewTracer

func NewTracer() *tracerS

NewTracer initializes a new tracer with default options

func NewTracerWithEverything

func NewTracerWithEverything(options *Options, recorder SpanRecorder) *tracerS

NewTracerWithEverything initializes and configures a new tracer. It uses instana.DefaultOptions() if nil is provided

func NewTracerWithOptions

func NewTracerWithOptions(options *Options) *tracerS

NewTracerWithOptions initializes and configures a new tracer that collects and sends spans to the agent

func ParseID added in v1.8.0

func ParseID(header string) (int64, error)

ParseID converts an header context value into an Instana ID. More specifically, this converts an unsigned 64 bit hex value into a signed 64bit integer.

func ParseLongID added in v1.24.0

func ParseLongID(header string) (hi int64, lo int64, err error)

ParseLongID converts an header context value into a 128-bit Instana ID. Both high and low quad words are returned as signed integers.

func Ready added in v1.36.0

func Ready() bool

Ready returns whether the Instana collector is ready to collect and send data to the agent

func RoundTripper added in v1.8.0

func RoundTripper(sensor TracerLogger, original http.RoundTripper) http.RoundTripper

RoundTripper wraps an existing http.RoundTripper and injects the tracing headers into the outgoing request. If the original RoundTripper is nil, the http.DefaultTransport will be used.

Example

This example demonstrates how to instrument an HTTP client with Instana

package main

import (
	"context"
	"net/http"

	instana "github.com/instana/go-sensor"
)

func main() {
	// Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended
	// to use a single instance throughout your application
	sensor := instana.NewSensor("my-http-client")
	span := sensor.Tracer().StartSpan("entry")

	// Make sure to finish the span so it can be properly recorded in the backend
	defer span.Finish()

	// http.DefaultTransport is used as a default RoundTripper, however you can provide
	// your own implementation
	client := &http.Client{
		Transport: instana.RoundTripper(sensor, nil),
	}

	// Inject parent span into the request context
	ctx := instana.ContextWithSpan(context.Background(), span)
	req, _ := http.NewRequest("GET", "https://www.instana.com", nil)

	// Execute request as usual
	client.Do(req.WithContext(ctx))
}
Output:

func SQLInstrumentAndOpen added in v1.43.0

func SQLInstrumentAndOpen(sensor TracerLogger, driverName, dataSourceName string) (*sql.DB, error)

SQLInstrumentAndOpen returns instrumented `*sql.DB`. It takes already registered `driver.Driver` by name, instruments it and additionally registers it with different name. After that it returns instrumented `*sql.DB` or error if any.

This function can be used as a convenient shortcut for InstrumentSQLDriver and SQLOpen functions. The main difference is that this approach will use the already registered driver and using InstrumentSQLDriver requires to explicitly provide an instance of the driver to instrument.

func SQLOpen added in v1.15.0

func SQLOpen(driverName, dataSourceName string) (*sql.DB, error)

SQLOpen is a convenience wrapper for `sql.Open()` to use the instrumented version of a driver previosly registered using `instana.InstrumentSQLDriver()`

Example

This example demonstrates how to instrument an *sql.DB instance created with sql.Open()

// Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended
// to use a single instance throughout your application
sensor := instana.NewSensor("my-http-client")

// Instrument the driver. Normally this would be a type provided by the driver library, e.g.
// pq.Driver{} or mysql.Driver{}, but here we use a test mock to avoid bringing external dependencies
instana.InstrumentSQLDriver(sensor, "your_db_driver", sqlDriver{})

// Replace sql.Open() with instana.SQLOpen()
db, _ := instana.SQLOpen("your_db_driver", "driver connection string")

// Inject parent span into the context
span := sensor.Tracer().StartSpan("entry")
ctx := instana.ContextWithSpan(context.Background(), span)

// Query the database, passing the context containing the active span
db.QueryContext(ctx, "SELECT * FROM users;")

// SQL queries that are not expected to return a result set are also supported
db.ExecContext(ctx, "UPDATE users SET last_seen_at = NOW();")
Output:

func SendDefaultServiceEvent

func SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration)

SendDefaultServiceEvent sends a default event which already contains the service and host

func SendHostEvent

func SendHostEvent(title string, text string, sev severity, duration time.Duration)

SendHostEvent sends an event on the current host

func SendServiceEvent

func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration)

SendServiceEvent sends an event on a specific service

func SetLogger added in v1.8.0

func SetLogger(l LeveledLogger)

SetLogger configures the default logger to be used by Instana go-sensor. Note that changing the logger will not affect already initialized instana.Sensor instances. To make them use the new logger please call (instana.TracerLogger).SetLogger() explicitly.

func ShutdownSensor added in v1.46.0

func ShutdownSensor()

ShutdownSensor cleans up the internal global sensor reference. The next time that instana.InitSensor is called, directly or indirectly, the internal sensor will be reinitialized.

func SpanFromContext added in v1.7.0

func SpanFromContext(ctx context.Context) (ot.Span, bool)

SpanFromContext retrieves previously stored active span from context. If there is no span, this method returns false.

func StartMetrics added in v1.55.0

func StartMetrics(options *Options)

StartMetrics initializes the communication with the agent. Then it starts collecting and reporting metrics to the agent. Calling StartMetrics multiple times has no effect and the function will simply return, and provided options will not be reapplied.

func StartSQLSpan added in v1.58.0

func StartSQLSpan(ctx context.Context, conn DbConnDetails, query string, sensor TracerLogger) (sp ot.Span, dbKey string)

StartSQLSpan creates a span based on DbConnDetails and a query, and attempts to detect which kind of database it belongs. If a database is detected and it is already part of the registered spans, the span details will be specific to that database. Otherwise, the span will have generic database fields.

func SuppressTracing added in v1.11.0

func SuppressTracing() ot.Tag

SuppressTracing returns an opentracing.Tag to mark the span and any of its child spans as not to be sent to the agent

func TracingHandlerFunc added in v1.8.0

func TracingHandlerFunc(sensor TracerLogger, pathTemplate string, handler http.HandlerFunc) http.HandlerFunc

TracingHandlerFunc is an HTTP middleware that captures the tracing data and ensures trace context propagation via OpenTracing headers. The pathTemplate parameter, when provided, will be added to the span as a template string used to match the route containing variables, regular expressions, etc.

The wrapped handler will also propagate the W3C trace context (https://www.w3.org/TR/trace-context/) if found in request.

Example

This example demonstrates how to instrument an HTTP handler with Instana and register it in http.DefaultServeMux

package main

import (
	"net/http"

	instana "github.com/instana/go-sensor"
)

func main() {
	// Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended
	// to use a single instance throughout your application
	sensor := instana.NewSensor("my-http-server")

	http.HandleFunc("/", instana.TracingNamedHandlerFunc(sensor, "root", "/", func(w http.ResponseWriter, req *http.Request) {
		// handler code
	}))
}
Output:

func TracingNamedHandlerFunc added in v1.35.0

func TracingNamedHandlerFunc(sensor TracerLogger, routeID, pathTemplate string, handler http.HandlerFunc) http.HandlerFunc

TracingNamedHandlerFunc is an HTTP middleware that similarly to instana.TracingHandlerFunc() captures the tracing data, while allowing to provide a unique route indetifier to be associated with each request.

func WrapSQLConnector added in v1.15.0

func WrapSQLConnector(sensor TracerLogger, name string, connector driver.Connector) *wrappedSQLConnector

WrapSQLConnector wraps an existing sql.Connector and instruments the DB calls made using it

Example

This example demonstrates how to instrument an *sql.DB instance created with sql.OpenDB() and driver.Connector

// Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended
// to use a single instance throughout your application
sensor := instana.NewSensor("my-http-client")

// Instrument the connector. Normally this would be a type provided by the driver library.
// Here we use a test mock to avoid bringing external dependencies.
//
// Note that instana.WrapSQLConnector() requires the connection string to send it later
// along with database spans.
connector := instana.WrapSQLConnector(sensor, "driver connection string", &sqlConnector{})

// Use wrapped connector to initialize the database client. Note that
db := sql.OpenDB(connector)

// Inject parent span into the context
span := sensor.Tracer().StartSpan("entry")
ctx := instana.ContextWithSpan(context.Background(), span)

// Query the database, passing the context containing the active span
db.QueryContext(ctx, "SELECT * FROM users;")

// SQL queries that are not expected to return a result set are also supported
db.ExecContext(ctx, "UPDATE users SET last_seen_at = NOW();")
Output:

Types

type AWSDynamoDBSpanData added in v1.26.0

type AWSDynamoDBSpanData struct {
	SpanData
	Tags AWSDynamoDBSpanTags `json:"dynamodb"`
}

AWSDynamoDBSpanData represents the `data` section of a AWS DynamoDB span sent within an OT span document

func (AWSDynamoDBSpanData) Kind added in v1.26.0

func (d AWSDynamoDBSpanData) Kind() SpanKind

Kind returns the span kind for a AWS DynamoDB span

type AWSDynamoDBSpanTags added in v1.26.0

type AWSDynamoDBSpanTags struct {
	// Table is the name of DynamoDB table
	Table string `json:"table,omitempty"`
	// Operation is the operation name
	Operation string `json:"op,omitempty"`
	// Error is an optional name returned by AWS API
	Error string `json:"error,omitempty"`
	// Region is a region from the AWS session config
	Region string `json:"region,omitempty"`
}

AWSDynamoDBSpanTags contains fields within the `data.sns` section of an OT span document

type AWSInvokeSpanTags added in v1.29.0

type AWSInvokeSpanTags struct {
	// FunctionName is a name of the function which is invoked
	FunctionName string `json:"function"`
	// InvocationType if equal to `Event`, means it is an async invocation
	InvocationType string `json:"type"`
	// Error is an optional error returned by AWS API
	Error string `json:"error,omitempty"`
}

AWSInvokeSpanTags contains fields within the `aws.lambda.invoke` section of an OT span document

type AWSLambdaCloudWatchEventTags added in v1.23.0

type AWSLambdaCloudWatchEventTags struct {
	// ID is the ID of the event
	ID string `json:"id"`
	// Resources contains the event resources
	Resources []string `json:"resources"`
	// More is set to true if the event resources list was truncated
	More bool `json:"more,omitempty"`
}

AWSLambdaCloudWatchEventTags contains fields within the `data.lambda.cw.events` section of an OT span document

func (AWSLambdaCloudWatchEventTags) IsZero added in v1.23.0

func (tags AWSLambdaCloudWatchEventTags) IsZero() bool

IsZero returns true if an AWSCloudWatchEventTags struct was populated with event data

type AWSLambdaCloudWatchLogsTags added in v1.23.0

type AWSLambdaCloudWatchLogsTags struct {
	Group         string   `json:"group"`
	Stream        string   `json:"stream"`
	Events        []string `json:"events"`
	More          bool     `json:"more,omitempty"`
	DecodingError string   `json:"decodingError,omitempty"`
}

AWSLambdaCloudWatchLogsTags contains fields within the `data.lambda.cw.logs` section of an OT span document

func (AWSLambdaCloudWatchLogsTags) IsZero added in v1.23.0

func (tags AWSLambdaCloudWatchLogsTags) IsZero() bool

IsZero returns true if an AWSLambdaCloudWatchLogsTags struct was populated with logs data

type AWSLambdaCloudWatchSpanTags added in v1.23.0

type AWSLambdaCloudWatchSpanTags struct {
	Events *AWSLambdaCloudWatchEventTags `json:"events,omitempty"`
	Logs   *AWSLambdaCloudWatchLogsTags  `json:"logs,omitempty"`
}

AWSLambdaCloudWatchSpanTags contains fields within the `data.lambda.cw` section of an OT span document

func (AWSLambdaCloudWatchSpanTags) IsZero added in v1.23.0

func (tags AWSLambdaCloudWatchSpanTags) IsZero() bool

IsZero returns true if an AWSLambdaCloudWatchSpanTags struct was populated with event data

type AWSLambdaInvokeSpanData added in v1.29.0

type AWSLambdaInvokeSpanData struct {
	SpanData
	Tags AWSInvokeSpanTags `json:"aws.lambda.invoke"`
}

AWSLambdaInvokeSpanData represents the `data` section of a AWS Invoke span sent within an OT span document

func (AWSLambdaInvokeSpanData) Kind added in v1.29.0

Kind returns the span kind for a AWS SDK Invoke span

func (AWSLambdaInvokeSpanData) Type added in v1.29.0

Type returns the span type for an AWS SDK Invoke span

type AWSLambdaS3SpanTags added in v1.23.0

type AWSLambdaS3SpanTags struct {
	Events []AWSS3EventTags `json:"events,omitempty"`
}

AWSLambdaS3SpanTags contains fields within the `data.lambda.s3` section of an OT span document

func (AWSLambdaS3SpanTags) IsZero added in v1.23.0

func (tags AWSLambdaS3SpanTags) IsZero() bool

IsZero returns true if an AWSLambdaS3SpanTags struct was populated with events data

type AWSLambdaSQSSpanTags added in v1.23.0

type AWSLambdaSQSSpanTags struct {
	// Messages are message tags for an SQS event
	Messages []AWSSQSMessageTags `json:"messages"`
}

AWSLambdaSQSSpanTags contains fields within the `data.lambda.sqs` section of an OT span document

func (AWSLambdaSQSSpanTags) IsZero added in v1.23.0

func (tags AWSLambdaSQSSpanTags) IsZero() bool

IsZero returns true if an AWSLambdaSQSSpanTags struct was populated with messages data

type AWSLambdaSpanData added in v1.23.0

type AWSLambdaSpanData struct {
	Snapshot AWSLambdaSpanTags `json:"lambda"`
	HTTP     *HTTPSpanTags     `json:"http,omitempty"`
}

AWSLambdaSpanData is the base span data type for AWS Lambda entry spans

func (AWSLambdaSpanData) Kind added in v1.23.0

func (d AWSLambdaSpanData) Kind() SpanKind

Kind returns the span kind for an AWS Lambda span

func (AWSLambdaSpanData) Type added in v1.23.0

Type returns the span type for an AWS Lambda span

type AWSLambdaSpanTags added in v1.23.0

type AWSLambdaSpanTags struct {
	// ARN is the ARN of invoked AWS Lambda function with the version attached
	ARN string `json:"arn"`
	// Runtime is an Instana constant for this AWS lambda runtime (always "go")
	Runtime string `json:"runtime"`
	// Name is the name of invoked function
	Name string `json:"functionName,omitempty"`
	// Version is either the numeric version or $LATEST
	Version string `json:"functionVersion,omitempty"`
	// Trigger is the trigger event type (if any)
	Trigger string `json:"trigger,omitempty"`
	// ColdStart is true if this is the first time current instance of the function was invoked
	ColdStart bool `json:"coldStart,omitempty"`
	// MillisecondsLeft is a number of milliseconds until timeout
	MillisecondsLeft int `json:"msleft,omitempty"`
	// Error is an AWS Lambda specific error
	Error string `json:"error,omitempty"`
	// CloudWatch holds the details of a CloudWatch event associated with this lambda
	CloudWatch *AWSLambdaCloudWatchSpanTags `json:"cw,omitempty"`
	// S3 holds the details of a S3 events associated with this lambda
	S3 *AWSLambdaS3SpanTags
	// SQS holds the details of a SQS events associated with this lambda
	SQS *AWSLambdaSQSSpanTags
}

AWSLambdaSpanTags contains fields within the `data.lambda` section of an OT span document

type AWSS3EventTags added in v1.23.0

type AWSS3EventTags struct {
	Name   string `json:"event"`
	Bucket string `json:"bucket"`
	Object string `json:"object,omitempty"`
}

AWSS3EventTags represens metadata for an S3 event

type AWSS3SpanData added in v1.26.0

type AWSS3SpanData struct {
	SpanData
	Tags AWSS3SpanTags `json:"s3"`
}

AWSS3SpanData represents the `data` section of a AWS S3 span sent within an OT span document

func (AWSS3SpanData) Kind added in v1.26.0

func (d AWSS3SpanData) Kind() SpanKind

Kind returns the span kind for a AWS S3 span

type AWSS3SpanTags added in v1.26.0

type AWSS3SpanTags struct {
	// Region is the AWS region used to access S3
	Region string `json:"region,omitempty"`
	// Operation is the operation name, as defined by AWS S3 API
	Operation string `json:"op,omitempty"`
	// Bucket is the bucket name
	Bucket string `json:"bucket,omitempty"`
	// Key is the object key
	Key string `json:"key,omitempty"`
	// Error is an optional error returned by AWS API
	Error string `json:"error,omitempty"`
}

AWSS3SpanTags contains fields within the `data.s3` section of an OT span document

type AWSSNSSpanData added in v1.26.0

type AWSSNSSpanData struct {
	SpanData
	Tags AWSSNSSpanTags `json:"sns"`
}

AWSSNSSpanData represents the `data` section of a AWS SNS span sent within an OT span document

func (AWSSNSSpanData) Kind added in v1.26.0

func (d AWSSNSSpanData) Kind() SpanKind

Kind returns the span kind for a AWS SNS span

type AWSSNSSpanTags added in v1.26.0

type AWSSNSSpanTags struct {
	// TopicARN is the topic ARN of an SNS message
	TopicARN string `json:"topic,omitempty"`
	// TargetARN is the target ARN of an SNS message
	TargetARN string `json:"target,omitempty"`
	// Phone is the phone no. of an SNS message
	Phone string `json:"phone,omitempty"`
	// Subject is the subject of an SNS message
	Subject string `json:"subject,omitempty"`
	// Error is an optional error returned by AWS API
	Error string `json:"error,omitempty"`
}

AWSSNSSpanTags contains fields within the `data.sns` section of an OT span document

type AWSSQSMessageTags added in v1.23.0

type AWSSQSMessageTags struct {
	Queue string `json:"queue"`
}

AWSSQSMessageTags represents span tags for an SQS message delivery

type AWSSQSSpanData added in v1.26.0

type AWSSQSSpanData struct {
	SpanData
	Tags AWSSQSSpanTags `json:"sqs"`
}

AWSSQSSpanData represents the `data` section of a AWS SQS span sent within an OT span document

func (AWSSQSSpanData) Kind added in v1.26.0

func (d AWSSQSSpanData) Kind() SpanKind

Kind returns the span kind for a AWS SQS span

type AWSSQSSpanTags added in v1.26.0

type AWSSQSSpanTags struct {
	// Sort is the direction of the call, wither "entry" or "exit"
	Sort string `json:"sort,omitempty"`
	// Queue is the queue name
	Queue string `json:"queue,omitempty"`
	// Type is the operation name
	Type string `json:"type,omitempty"`
	// MessageGroupID is the message group ID specified while sending messages
	MessageGroupID string `json:"group,omitempty"`
	// Size is the optional batch size
	Size int `json:"size,omitempty"`
	// Error is an optional error returned by AWS API
	Error string `json:"error,omitempty"`
}

AWSSQSSpanTags contains fields within the `data.sqs` section of an OT span document

type AZFSpanData added in v1.48.0

type AZFSpanData struct {
	SpanData
	Tags AZFSpanTags `json:"azf"`
}

func (AZFSpanData) Kind added in v1.48.0

func (d AZFSpanData) Kind() SpanKind

Kind returns instana.EntrySpanKind for server spans and instana.ExitSpanKind otherwise

type AZFSpanTags added in v1.48.0

type AZFSpanTags struct {
	Name         string `json:"name,omitempty"`
	FunctionName string `json:"functionname,omitempty"`
	MethodName   string `json:"methodname,omitempty"`
	Trigger      string `json:"triggername,omitempty"`
	Runtime      string `json:"runtime,omitempty"`
	Error        string `json:"error,omitempty"`
}

type AgentClient added in v1.47.0

type AgentClient interface {
	Ready() bool
	SendMetrics(data acceptor.Metrics) error
	SendEvent(event *EventData) error
	SendSpans(spans []Span) error
	SendProfiles(profiles []autoprofile.Profile) error
	Flush(context.Context) error
}

type Collector added in v1.55.0

type Collector struct {
	LeveledLogger
	*Sensor
	// contains filtered or unexported fields
}

Collector is used to inject tracing information into requests

func (*Collector) Debug added in v1.55.0

func (c *Collector) Debug(v ...interface{})

Debug logs a debug message by calling LeveledLogger underneath

func (*Collector) Error added in v1.55.0

func (c *Collector) Error(v ...interface{})

Error logs a error message by calling LeveledLogger underneath

func (*Collector) Extract added in v1.55.0

func (c *Collector) Extract(format interface{}, carrier interface{}) (ot.SpanContext, error)

Extract() returns a SpanContext instance given `format` and `carrier`. It matches opentracing.Tracer.Extract.

func (*Collector) Flush added in v1.55.0

func (c *Collector) Flush(ctx context.Context) error

Flush sends all finished spans to the agent It matches instana.Tracer.Flush.

func (*Collector) Info added in v1.55.0

func (c *Collector) Info(v ...interface{})

Info logs an info message by calling LeveledLogger underneath

func (*Collector) Inject added in v1.55.0

func (c *Collector) Inject(sm ot.SpanContext, format interface{}, carrier interface{}) error

Inject() takes the `sm` SpanContext instance and injects it for propagation within `carrier`. The actual type of `carrier` depends on the value of `format`. It matches opentracing.Tracer.Inject

func (*Collector) LegacySensor added in v1.55.0

func (c *Collector) LegacySensor() *Sensor

LegacySensor returns a reference to Sensor that can be used for old instrumentations that still require it.

Example:

// Instrumenting HTTP incoming calls
c := instana.InitCollector("my-service")
http.HandleFunc("/", instana.TracingNamedHandlerFunc(c.LegacySensor(), "", "/{name}", handle))

func (*Collector) Options added in v1.55.0

func (c *Collector) Options() TracerOptions

Options gets the current tracer options It matches instana.Tracer.Options.

func (*Collector) SetLogger added in v1.59.0

func (c *Collector) SetLogger(l LeveledLogger)

SetLogger changes the Sensor logger and LeveledLogger both to satisfy TracerLogger

func (*Collector) StartSpan added in v1.55.0

func (c *Collector) StartSpan(operationName string, opts ...ot.StartSpanOption) ot.Span

Create, start, and return a new Span with the given `operationName` and incorporate the given StartSpanOption `opts`. (Note that `opts` borrows from the "functional options" pattern, per http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis)

It matches opentracing.Tracer.StartSpan.

func (*Collector) StartSpanWithOptions added in v1.55.0

func (c *Collector) StartSpanWithOptions(operationName string, opts ot.StartSpanOptions) ot.Span

StartSpanWithOptions creates and starts a span by setting Instana relevant data within the span. It matches instana.Tracer.StartSpanWithOptions.

func (*Collector) Warn added in v1.55.0

func (c *Collector) Warn(v ...interface{})

Warn logs a warning message by calling LeveledLogger underneath

type ContextSensitiveFunc deprecated added in v1.4.14

type ContextSensitiveFunc func(span ot.Span, ctx context.Context)

ContextSensitiveFunc is a SpanSensitiveFunc that also takes context.Context

Deprecated: use instana.ContextWithSpan() and instana.SpanFromContext() to inject and retrieve spans

type CosmosSpanData added in v1.60.0

type CosmosSpanData struct {
	SpanData
	Tags CosmosSpanTags `json:"cosmos"`
}

CosmosSpanData represents the `data` section of a Cosmos client span

func (CosmosSpanData) Kind added in v1.60.0

func (c CosmosSpanData) Kind() SpanKind

Kind returns the span kind for a Cosmos client span

type CosmosSpanTags added in v1.60.0

type CosmosSpanTags struct {
	ConnectionURL string `json:"con"`
	Database      string `json:"db"`
	Type          string `json:"type"`
	Sql           string `json:"cmd"`
	Object        string `json:"obj"`
	PartitionKey  string `json:"pk"`
	ReturnCode    string `json:"rt"`
	Error         string `json:"error,omitempty"`
}

CosmosSpanTags contains fields within the `data.cosmos` section of an OT span document

type CouchbaseSpanData added in v1.59.0

type CouchbaseSpanData struct {
	SpanData
	Tags CouchbaseSpanTags `json:"couchbase"`
}

CouchbaseSpanData represents the `data` section of a Couchbase client span

func (CouchbaseSpanData) Kind added in v1.59.0

func (c CouchbaseSpanData) Kind() SpanKind

Kind returns the span kind for a Couchbase client span

type CouchbaseSpanTags added in v1.59.0

type CouchbaseSpanTags struct {
	Bucket string `json:"bucket"`
	Host   string `json:"hostname"`
	Type   string `json:"type"`
	SQL    string `json:"sql"`

	Error string `json:"error,omitempty"`
}

CouchbaseSpanTags contains fields within the `data.couchbase` section of an OT span document

type CustomSpanData added in v1.28.0

type CustomSpanData struct {
	Tags map[string]interface{} `json:"tags,omitempty"`
}

CustomSpanData holds user-defined span tags

type DbConnDetails added in v1.54.0

type DbConnDetails struct {
	RawString    string
	Host, Port   string
	Schema       string
	User         string
	DatabaseName string
	Error        error
}

func ParseDBConnDetails added in v1.54.0

func ParseDBConnDetails(connStr string) DbConnDetails

type EUMCorrelationData added in v1.16.0

type EUMCorrelationData struct {
	Type string
	ID   string
}

EUMCorrelationData represents the data sent by the Instana End-User Monitoring script integrated into frontend

type EntityData

type EntityData acceptor.GoProcessData

EntityData struct to hold snapshot data

type EventData

type EventData struct {
	Title string `json:"title"`
	Text  string `json:"text"`
	// Duration in milliseconds
	Duration int `json:"duration"`
	// Severity with value of -1, 5, 10 : see type severity
	Severity int    `json:"severity"`
	Plugin   string `json:"plugin,omitempty"`
	ID       string `json:"id,omitempty"`
	Host     string `json:"host"`
}

EventData is the construct serialized for the host agent

type GCPPubSubSpanData added in v1.21.0

type GCPPubSubSpanData struct {
	SpanData
	Tags GCPPubSubSpanTags `json:"gcps"`
}

GCPPubSubSpanData represents the `data` section of a Google Cloud Pub/Sub span sent within an OT span document

func (GCPPubSubSpanData) Kind added in v1.21.0

func (d GCPPubSubSpanData) Kind() SpanKind

Kind returns the span kind for a Google Cloud Pub/Sub span

type GCPPubSubSpanTags added in v1.21.0

type GCPPubSubSpanTags struct {
	ProjectID    string `json:"projid"`
	Operation    string `json:"op"`
	Topic        string `json:"top,omitempty"`
	Subscription string `json:"sub,omitempty"`
	MessageID    string `json:"msgid,omitempty"`
}

GCPPubSubSpanTags contains fields within the `data.gcps` section of an OT span document

type GCPStorageSpanData added in v1.18.0

type GCPStorageSpanData struct {
	SpanData
	Tags GCPStorageSpanTags `json:"gcs"`
}

GCPStorageSpanData represents the `data` section of a Google Cloud Storage span sent within an OT span document

func (GCPStorageSpanData) Kind added in v1.18.0

func (d GCPStorageSpanData) Kind() SpanKind

Kind returns the span kind for a Google Cloud Storage span

type GCPStorageSpanTags added in v1.18.0

type GCPStorageSpanTags struct {
	Operation          string `json:"op,omitempty"`
	Bucket             string `json:"bucket,omitempty"`
	Object             string `json:"object,omitempty"`
	Entity             string `json:"entity,omitempty"`
	Range              string `json:"range,omitempty"`
	SourceBucket       string `json:"sourceBucket,omitempty"`
	SourceObject       string `json:"sourceObject,omitempty"`
	DestinationBucket  string `json:"destinationBucket,omitempty"`
	DestinationObject  string `json:"destinationObject,omitempty"`
	NumberOfOperations string `json:"numberOfOperations,omitempty"`
	ProjectID          string `json:"projectId,omitempty"`
	AccessID           string `json:"accessId,omitempty"`
}

GCPStorageSpanTags contains fields within the `data.gcs` section of an OT span document

type GraphQLSpanData added in v1.50.0

type GraphQLSpanData struct {
	SpanData
	Tags GraphQLSpanTags `json:"graphql"`
	// contains filtered or unexported fields
}

GraphQLSpanData represents the `data` section of a GraphQL span sent within an OT span document

func (GraphQLSpanData) Kind added in v1.50.0

func (d GraphQLSpanData) Kind() SpanKind

Kind returns instana.EntrySpanKind for server spans and instana.ExitSpanKind otherwise

type GraphQLSpanTags added in v1.50.0

type GraphQLSpanTags struct {
	OperationName string              `json:"operationName,omitempty"`
	OperationType string              `json:"operationType,omitempty"`
	Fields        map[string][]string `json:"fields,omitempty"`
	Args          map[string][]string `json:"args,omitempty"`
	Error         string              `json:"error,omitempty"`
}

GraphQLSpanTags contains fields within the `data.graphql` section of an OT span document

type HTTPSpanData added in v1.9.0

type HTTPSpanData struct {
	SpanData
	Tags HTTPSpanTags `json:"http"`
	// contains filtered or unexported fields
}

HTTPSpanData represents the `data` section of an HTTP span sent within an OT span document

func (HTTPSpanData) Kind added in v1.28.0

func (d HTTPSpanData) Kind() SpanKind

Kind returns instana.EntrySpanKind for server spans and instana.ExitSpanKind otherwise

type HTTPSpanTags added in v1.9.0

type HTTPSpanTags struct {
	// Full request/response URL
	URL string `json:"url,omitempty"`
	// The HTTP status code returned with client/server response
	Status int `json:"status,omitempty"`
	// The HTTP method of the request
	Method string `json:"method,omitempty"`
	// Path is the path part of the request URL
	Path string `json:"path,omitempty"`
	// Params are the request query string parameters
	Params string `json:"params,omitempty"`
	// Headers are the captured request/response headers
	Headers map[string]string `json:"header,omitempty"`
	// PathTemplate is the raw template string used to route the request
	PathTemplate string `json:"path_tpl,omitempty"`
	// RouteID is an optional name/identifier for the matched route
	RouteID string `json:"route_id,omitempty"`
	// The name:port of the host to which the request had been sent
	Host string `json:"host,omitempty"`
	// The name of the protocol used for request ("http" or "https")
	Protocol string `json:"protocol,omitempty"`
	// The message describing an error occurred during the request handling
	Error string `json:"error,omitempty"`
}

HTTPSpanTags contains fields within the `data.http` section of an OT span document

type KafkaSpanData added in v1.9.0

type KafkaSpanData struct {
	SpanData
	Tags KafkaSpanTags `json:"kafka"`
	// contains filtered or unexported fields
}

KafkaSpanData represents the `data` section of an Kafka span sent within an OT span document

func (KafkaSpanData) Kind added in v1.28.0

func (d KafkaSpanData) Kind() SpanKind

Kind returns instana.ExitSpanKind for producer spans and instana.EntrySpanKind otherwise

type KafkaSpanTags added in v1.9.0

type KafkaSpanTags struct {
	// Kafka topic
	Service string `json:"service"`
	// The access mode:, either "send" for publisher or "consume" for consumer
	Access string `json:"access"`
}

KafkaSpanTags contains fields within the `data.kafka` section of an OT span document

type LeveledLogger added in v1.8.0

type LeveledLogger interface {
	Debug(v ...interface{})
	Info(v ...interface{})
	Warn(v ...interface{})
	Error(v ...interface{})
}

LeveledLogger is an interface of a generic logger that support different message levels. By default instana.Sensor uses logger.Logger with log.Logger as an output, however this interface is also compatible with such popular loggers as github.com/sirupsen/logrus.Logger and go.uber.org/zap.SugaredLogger

type LogSpanData added in v1.31.0

type LogSpanData struct {
	SpanData
	Tags LogSpanTags `json:"log"`
}

LogSpanData represents the `data` section of a logging span

func (LogSpanData) Kind added in v1.31.0

func (d LogSpanData) Kind() SpanKind

Kind returns the span kind for a logging span

type LogSpanTags added in v1.31.0

type LogSpanTags struct {
	// Message is a string to log
	Message string `json:"message"`
	// Level is an optional log level for this record, e.g. INFO
	Level string `json:"level,omitempty"`
	// Logger is an optional logger name
	Logger string `json:"logger,omitempty"`
	// Error is an optional error string (if any)
	Error string `json:"parameters,omitempty"`
}

LogSpanTags contains fields within the `data.log` section of an OT span document

type Matcher added in v1.17.0

type Matcher interface {
	Match(s string) bool
}

Matcher verifies whether a string meets predefined conditions

func DefaultSecretsMatcher added in v1.17.0

func DefaultSecretsMatcher() Matcher

DefaultSecretsMatcher returns the default secrets matcher, that matches strings containing "key", "password" and "secret" ignoring the case

func NamedMatcher added in v1.17.0

func NamedMatcher(name string, list []string) (Matcher, error)

NamedMatcher returns a secrets matcher supported by Instana host agent configuration

See https://www.instana.com/docs/setup_and_manage/host_agent/configuration/#secrets

type MemoryS

type MemoryS acceptor.MemoryStats

MemoryS struct to hold snapshot data

type MetricsS

type MetricsS acceptor.Metrics

MetricsS struct to hold snapshot data

type MongoDBSpanData added in v1.32.0

type MongoDBSpanData struct {
	SpanData
	Tags MongoDBSpanTags `json:"mongo"`
}

MongoDBSpanData represents the `data` section of a MongoDB client span

func (MongoDBSpanData) Kind added in v1.32.0

func (d MongoDBSpanData) Kind() SpanKind

Kind returns the span kind for a MongoDB client span

type MongoDBSpanTags added in v1.32.0

type MongoDBSpanTags struct {
	// Service is the MongoDB server address in form of host:port
	Service string `json:"service"`
	// Namespace is the namespace name
	Namespace string `json:"namespace"`
	// Command is the name of the command initiated the span
	Command string `json:"command"`
	// Query is an optional query passed with command
	Query string `json:"query,omitempty"`
	// JSON is an optional JSON aggregation provided with command
	JSON string `json:"json,omitempty"`
	// Filter is an optional filter passed with command
	Filter string `json:"filter,omitempty"`
	// Error is an optional error message
	Error string `json:"error,omitempty"`
}

MongoDBSpanTags contains fields within the `data.mongo` section of an OT span document

type MySQLSpanData added in v1.57.0

type MySQLSpanData struct {
	SpanData
	Tags MySQLSpanTags `json:"mysql"`
}

MySQLSpanData represents the `data` section of a MySQL client span

func (MySQLSpanData) Kind added in v1.57.0

func (d MySQLSpanData) Kind() SpanKind

Kind returns the span kind for a MySQL client span

type MySQLSpanTags added in v1.57.0

type MySQLSpanTags struct {
	Host string `json:"host"`
	Port string `json:"port"`
	DB   string `json:"db"`
	User string `json:"user"`
	Stmt string `json:"stmt"`

	Error string `json:"error,omitempty"`
}

MySQLSpanTags contains fields within the `data.mysql` section of an OT span document

type Options

type Options struct {
	// Service is the global service name that will be used to identify the program in the Instana backend
	Service string
	// AgentHost is the Instana host agent host name
	//
	// Note: This setting has no effect in serverless environments. To specify the serverless acceptor endpoint,
	// INSTANA_ENDPOINT_URL env var. See https://www.instana.com/docs/reference/environment_variables/#serverless-monitoring
	// for more details.
	AgentHost string
	// AgentPort is the Instana host agent port
	//
	// Note: This setting has no effect in serverless environments. To specify the serverless acceptor endpoint,
	// INSTANA_ENDPOINT_URL env var. See https://www.instana.com/docs/reference/environment_variables/#serverless-monitoring
	// for more details.
	AgentPort int
	// MaxBufferedSpans is the maximum number of spans to buffer
	MaxBufferedSpans int
	// ForceTransmissionStartingAt is the number of spans to collect before flushing the buffer to the agent
	ForceTransmissionStartingAt int
	// LogLevel is the initial logging level for the logger used by Instana tracer. The valid log levels are
	// logger.{Error,Warn,Info,Debug}Level provided by the github.com/instana/go-sensor/logger package.
	//
	// Note: this setting is only used to initialize the default logger and has no effect if a custom logger is set via instana.SetLogger()
	LogLevel int
	// EnableAutoProfile enables automatic continuous process profiling when set to true
	EnableAutoProfile bool
	// MaxBufferedProfiles is the maximum number of profiles to buffer
	MaxBufferedProfiles int
	// IncludeProfilerFrames is whether to include profiler calls into the profile or not
	IncludeProfilerFrames bool
	// Tracer contains tracer-specific configuration used by all tracers
	Tracer TracerOptions
	// AgentClient client to communicate with the agent. In most cases, there is no need to provide it.
	// If it is nil the default implementation will be used.
	AgentClient AgentClient

	// Recorder records and manages spans. When this option is not set, instana.NewRecorder() will be used.
	Recorder SpanRecorder
	// contains filtered or unexported fields
}

Options allows the user to configure the to-be-initialized sensor

func DefaultOptions added in v1.11.0

func DefaultOptions() *Options

DefaultOptions returns the default set of options to configure Instana sensor. The service name is set to the name of current executable, the MaxBufferedSpans and ForceTransmissionStartingAt are set to instana.DefaultMaxBufferedSpans and instana.DefaultForceSpanSendAt correspondigly. The AgentHost and AgentPort are taken from the env INSTANA_AGENT_HOST and INSTANA_AGENT_PORT if set, and default to localhost and 42699 otherwise.

type PostgreSQLSpanData added in v1.41.0

type PostgreSQLSpanData struct {
	SpanData
	Tags PostgreSQLSpanTags `json:"pg"`
}

PostgreSQLSpanData represents the `data` section of a PostgreSQL client span

func (PostgreSQLSpanData) Kind added in v1.41.0

func (d PostgreSQLSpanData) Kind() SpanKind

Kind returns the span kind for a PostgreSQL client span

type PostgreSQLSpanTags added in v1.57.0

type PostgreSQLSpanTags struct {
	Host string `json:"host"`
	Port string `json:"port"`
	DB   string `json:"db"`
	User string `json:"user"`
	Stmt string `json:"stmt"`

	Error string `json:"error,omitempty"`
}

PostgreSQLSpanTags contains fields within the `data.pg` section of an OT span document

type RPCSpanData added in v1.9.0

type RPCSpanData struct {
	SpanData
	Tags RPCSpanTags `json:"rpc"`
	// contains filtered or unexported fields
}

RPCSpanData represents the `data` section of an RPC span sent within an OT span document

func (RPCSpanData) Kind added in v1.28.0

func (d RPCSpanData) Kind() SpanKind

Kind returns instana.EntrySpanKind for server spans and instana.ExitSpanKind otherwise

type RPCSpanTags added in v1.9.0

type RPCSpanTags struct {
	// The name of the remote host for an RPC call
	Host string `json:"host,omitempty"`
	// The port of the remote host for an RPC call
	Port string `json:"port,omitempty"`
	// The name of the remote method to invoke
	Call string `json:"call,omitempty"`
	// The type of an RPC call, e.g. either "unary" or "stream" for GRPC requests
	CallType string `json:"call_type,omitempty"`
	// The RPC flavor used for this call, e.g. "grpc" for GRPC requests
	Flavor string `json:"flavor,omitempty"`
	// The message describing an error occurred during the request handling
	Error string `json:"error,omitempty"`
}

RPCSpanTags contains fields within the `data.rpc` section of an OT span document

type RabbitMQSpanData added in v1.42.0

type RabbitMQSpanData struct {
	SpanData
	Tags RabbitMQSpanTags `json:"rabbitmq"`
	// contains filtered or unexported fields
}

RabbitMQSpanData represents the `data` section of an RabbitMQ span

func (RabbitMQSpanData) Kind added in v1.42.0

func (d RabbitMQSpanData) Kind() SpanKind

Kind returns instana.ExitSpanKind for producer spans and instana.EntrySpanKind otherwise

type RabbitMQSpanTags added in v1.42.0

type RabbitMQSpanTags struct {
	// The RabbitMQ exchange name
	Exchange string `json:"exchange"`
	// The routing key
	Key string `json:"key"`
	// Indicates wether the message is being produced or consumed
	Sort string `json:"sort"`
	// The AMQP URI used to establish a connection to RabbitMQ
	Address string `json:"address"`
	// Error is the optional error that can be thrown by RabbitMQ when executing a command
	Error string `json:"error,omitempty"`
}

RabbitMQSpanTags contains fields within the `data.rabbitmq` section

type Recorder

type Recorder struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Recorder accepts spans, processes and queues them for delivery to the backend.

func NewRecorder

func NewRecorder() *Recorder

NewRecorder initializes a new span recorder

func NewTestRecorder

func NewTestRecorder() *Recorder

NewTestRecorder initializes a new span recorder that keeps all collected until they are requested. This recorder does not send spans to the agent (used for testing)

func (*Recorder) Flush added in v1.23.0

func (r *Recorder) Flush(ctx context.Context) error

Flush sends queued spans to the agent

func (*Recorder) GetQueuedSpans

func (r *Recorder) GetQueuedSpans() []Span

GetQueuedSpans returns a copy of the queued spans and clears the queue.

func (*Recorder) QueuedSpansCount

func (r *Recorder) QueuedSpansCount() int

QueuedSpansCount returns the number of queued spans

Used only in tests currently.

func (*Recorder) RecordSpan

func (r *Recorder) RecordSpan(span *spanS)

RecordSpan accepts spans to be recorded and added to the span queue for eventual reporting to the host agent.

type RedisSpanData added in v1.41.1

type RedisSpanData struct {
	SpanData
	Tags RedisSpanTags `json:"redis"`
}

RedisSpanData represents the `data` section of a Redis client span

func (RedisSpanData) Kind added in v1.41.1

func (d RedisSpanData) Kind() SpanKind

Kind returns the span kind for a Redis client span

type RedisSpanTags added in v1.41.1

type RedisSpanTags struct {
	// Connection is the host and port where the Redis server is running
	Connection string `json:"connection"`
	// Command is the Redis command being executed
	Command string `json:"command"`
	// Subcommands is the list of commands queued when a transaction starts, eg: by using the MULTI command
	Subcommands []string `json:"subCommands,omitempty"`
	// Error is the optional error that can be thrown by Redis when executing a command
	Error string `json:"error,omitempty"`
}

RedisSpanTags contains fields within the `data.redis` section of an OT span document

type RegisteredSpanType added in v1.9.0

type RegisteredSpanType string

RegisteredSpanType represents the span type supported by Instana

func (RegisteredSpanType) TagsNames added in v1.28.0

func (st RegisteredSpanType) TagsNames() map[string]struct{}

TagsNames returns a set of tag names known to the registered span type

type SDKSpanData added in v1.9.0

type SDKSpanData struct {
	// Deprecated
	SpanData `json:"-"`

	Service string      `json:"service,omitempty"`
	Tags    SDKSpanTags `json:"sdk"`
	// contains filtered or unexported fields
}

SDKSpanData represents the `data` section of an SDK span sent within an OT span document

func (SDKSpanData) Kind added in v1.28.0

func (d SDKSpanData) Kind() SpanKind

Kind returns the kind of the span. It handles the github.com/opentracing/opentracing-go/ext.SpanKindEnum values as well as generic "entry" and "exit"

func (SDKSpanData) Type added in v1.28.0

Type returns the registered span type suitable for use as the value of `n` field.

type SDKSpanTags added in v1.9.0

type SDKSpanTags struct {
	Name      string                 `json:"name"`
	Type      string                 `json:"type,omitempty"`
	Arguments string                 `json:"arguments,omitempty"`
	Return    string                 `json:"return,omitempty"`
	Custom    map[string]interface{} `json:"custom,omitempty"`
}

SDKSpanTags contains fields within the `data.sdk` section of an OT span document

type Sensor added in v1.4.14

type Sensor struct {
	// contains filtered or unexported fields
}

Sensor is used to inject tracing information into requests

func NewSensor added in v1.4.14

func NewSensor(serviceName string) *Sensor

NewSensor creates a new Sensor

func NewSensorWithTracer added in v1.7.0

func NewSensorWithTracer(tracer ot.Tracer) *Sensor

NewSensorWithTracer returns a new Sensor that uses provided tracer to report spans

func (*Sensor) Debug added in v1.55.0

func (s *Sensor) Debug(v ...interface{})

Debug logs a debug message by calling LeveledLogger underneath

func (*Sensor) Error added in v1.55.0

func (s *Sensor) Error(v ...interface{})

Error logs a error message by calling LeveledLogger underneath

func (*Sensor) Extract added in v1.55.0

func (s *Sensor) Extract(format interface{}, carrier interface{}) (ot.SpanContext, error)

Extract() returns a SpanContext instance given `format` and `carrier`. It matches opentracing.Tracer.Extract.

func (*Sensor) Flush added in v1.55.0

func (s *Sensor) Flush(ctx context.Context) error

Flush sends all finished spans to the agent It matches instana.Tracer.Flush.

func (*Sensor) Info added in v1.55.0

func (s *Sensor) Info(v ...interface{})

Info logs an info message by calling LeveledLogger underneath

func (*Sensor) Inject added in v1.55.0

func (s *Sensor) Inject(sm ot.SpanContext, format interface{}, carrier interface{}) error

Inject() takes the `sm` SpanContext instance and injects it for propagation within `carrier`. The actual type of `carrier` depends on the value of `format`. It matches opentracing.Tracer.Inject

func (*Sensor) LegacySensor added in v1.55.0

func (s *Sensor) LegacySensor() *Sensor

LegacySensor returns a reference to Sensor.

func (*Sensor) Logger added in v1.8.0

func (s *Sensor) Logger() LeveledLogger

Logger returns the logger instance for this sensor

func (*Sensor) Options added in v1.55.0

func (s *Sensor) Options() TracerOptions

Options gets the current tracer options It matches instana.Tracer.Options.

func (*Sensor) SetLogger added in v1.8.0

func (s *Sensor) SetLogger(l LeveledLogger)

SetLogger sets the logger for this sensor

func (*Sensor) StartSpan added in v1.55.0

func (s *Sensor) StartSpan(operationName string, opts ...ot.StartSpanOption) ot.Span

Create, start, and return a new Span with the given `operationName` and incorporate the given StartSpanOption `opts`. (Note that `opts` borrows from the "functional options" pattern, per http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis)

It matches opentracing.Tracer.StartSpan.

func (*Sensor) StartSpanWithOptions added in v1.55.0

func (s *Sensor) StartSpanWithOptions(operationName string, opts ot.StartSpanOptions) ot.Span

StartSpanWithOptions creates and starts a span by setting Instana relevant data within the span. It matches instana.Tracer.StartSpanWithOptions.

func (*Sensor) TraceHandler deprecated added in v1.4.14

func (s *Sensor) TraceHandler(name, pattern string, handler http.HandlerFunc) (string, http.HandlerFunc)

TraceHandler is similar to TracingHandler in regards, that it wraps an existing http.HandlerFunc into a named instance to support capturing tracing information and data. The returned values are compatible with handler registration methods, e.g. http.Handle()

Deprecated: please use instana.TracingHandlerFunc() instead

func (*Sensor) Tracer added in v1.7.1

func (s *Sensor) Tracer() ot.Tracer

Tracer returns the tracer instance for this sensor

func (*Sensor) TracingHandler deprecated added in v1.4.14

func (s *Sensor) TracingHandler(name string, handler http.HandlerFunc) http.HandlerFunc

TracingHandler wraps an existing http.HandlerFunc into a named instance to support capturing tracing information and response data

Deprecated: please use instana.TracingHandlerFunc() instead

func (*Sensor) TracingHttpRequest deprecated added in v1.4.14

func (s *Sensor) TracingHttpRequest(name string, parent, req *http.Request, client http.Client) (*http.Response, error)

TracingHttpRequest wraps an existing http.Request instance into a named instance to inject tracing and span header information into the actual HTTP wire transfer

Deprecated: please use instana.RoundTripper() instead

func (*Sensor) Warn added in v1.55.0

func (s *Sensor) Warn(v ...interface{})

Warn logs a warning message by calling LeveledLogger underneath

func (*Sensor) WithTracingContext deprecated added in v1.4.14

func (s *Sensor) WithTracingContext(name string, w http.ResponseWriter, req *http.Request, f ContextSensitiveFunc)

WithTracingContext executes the given ContextSensitiveFunc and executes it under the scope of a newly created context.Context, that provides access to the parent span as 'parentSpan'.

Deprecated: please use instana.TracingHandlerFunc() to instrument an HTTP handler

func (*Sensor) WithTracingSpan deprecated added in v1.4.14

func (s *Sensor) WithTracingSpan(operationName string, w http.ResponseWriter, req *http.Request, f SpanSensitiveFunc)

WithTracingSpan takes the given SpanSensitiveFunc and executes it under the scope of a child span, which is injected as an argument when calling the function. It uses the name of the caller as a span operation name unless a non-empty value is provided

Deprecated: please use instana.TracingHandlerFunc() to instrument an HTTP handler

type SensorLogger added in v1.55.0

type SensorLogger interface {
	Tracer() ot.Tracer
	Logger() LeveledLogger
	SetLogger(l LeveledLogger)
}

type SnapshotCollector added in v1.13.2

type SnapshotCollector struct {
	ServiceName        string
	CollectionInterval time.Duration
	// contains filtered or unexported fields
}

SnapshotCollector returns a snapshot of Go runtime

func (*SnapshotCollector) Collect added in v1.13.2

func (sc *SnapshotCollector) Collect() *acceptor.RuntimeInfo

Collect returns a snaphot of current runtime state. Any call this method made before the next interval elapses will return nil

type SnapshotS

type SnapshotS acceptor.RuntimeInfo

SnapshotS struct to hold snapshot data

type Span added in v1.9.0

type Span struct {
	TraceID         int64
	TraceIDHi       int64
	ParentID        int64
	SpanID          int64
	Ancestor        *TraceReference
	Timestamp       uint64
	Duration        uint64
	Name            string
	From            *fromS
	Batch           *batchInfo
	Kind            int
	Ec              int
	Data            typedSpanData
	Synthetic       bool
	CorrelationType string
	CorrelationID   string
	ForeignTrace    bool
}

Span represents the OpenTracing span document to be sent to the agent

func (Span) MarshalJSON added in v1.24.0

func (sp Span) MarshalJSON() ([]byte, error)

MarshalJSON serializes span to JSON for sending it to Instana

type SpanContext

type SpanContext struct {
	// The higher 4 bytes of a 128-bit trace ID
	TraceIDHi int64
	// A probabilistically unique identifier for a [multi-span] trace.
	TraceID int64
	// A probabilistically unique identifier for a span.
	SpanID int64
	// An optional parent span ID, 0 if this is the root span context.
	ParentID int64
	// Optional links to traces relevant to this context, i.e. an indirect parent
	Links []SpanReference
	// Whether the trace is sampled.
	Sampled bool
	// Whether the trace is suppressed and should not be sent to the agent.
	Suppressed bool
	// The span's associated baggage.
	Baggage map[string]string // initialized on first use
	// The W3C trace context
	W3CContext w3ctrace.Context
	// Whether the used trace ID came from 3rd party, e.g. W3C Trace Context
	ForeignTrace bool
	// Correlation is the correlation data sent by the frontend EUM script
	Correlation EUMCorrelationData
}

SpanContext holds the basic Span metadata.

func NewRootSpanContext added in v1.9.0

func NewRootSpanContext() SpanContext

NewRootSpanContext initializes a new root span context issuing a new trace ID

func NewSpanContext added in v1.9.0

func NewSpanContext(parent SpanContext) SpanContext

NewSpanContext initializes a new child span context from its parent. It will ignore the parent context if it contains neither Instana trace and span IDs nor a W3C trace context

func (SpanContext) Clone added in v1.9.0

func (sc SpanContext) Clone() SpanContext

Clone returns a deep copy of a SpanContext

func (SpanContext) ForeachBaggageItem

func (sc SpanContext) ForeachBaggageItem(handler func(k, v string) bool)

ForeachBaggageItem belongs to the opentracing.SpanContext interface

func (SpanContext) IsZero added in v1.27.0

func (sc SpanContext) IsZero() bool

IsZero returns true if an instance of SpanContext is a zero-value

func (SpanContext) WithBaggageItem

func (sc SpanContext) WithBaggageItem(key, val string) SpanContext

WithBaggageItem returns an entirely new SpanContext with the given key:value baggage pair set.

type SpanData added in v1.9.0

type SpanData struct {
	Service string          `json:"service,omitempty"`
	Custom  *CustomSpanData `json:"sdk.custom,omitempty"`
	// contains filtered or unexported fields
}

SpanData contains fields to be sent in the `data` section of an OT span document. These fields are common for all span types.

func NewSpanData added in v1.9.0

func NewSpanData(span *spanS, st RegisteredSpanType) SpanData

NewSpanData initializes a new span data from tracer span

func (SpanData) Type added in v1.9.0

func (d SpanData) Type() RegisteredSpanType

Type returns the registered span type suitable for use as the value of `n` field.

type SpanKind added in v1.9.0

type SpanKind uint8

SpanKind represents values of field `k` in OpenTracing span representation. It represents the direction of the call associated with a span.

const (
	// The kind of a span associated with an inbound call, this must be the first span in the trace.
	EntrySpanKind SpanKind = iota + 1
	// The kind of a span associated with an outbound call, e.g. an HTTP client request, posting to a message bus, etc.
	ExitSpanKind
	// The default kind for a span that is associated with a call within the same service.
	IntermediateSpanKind
)

Valid span kinds

func (SpanKind) String added in v1.9.0

func (k SpanKind) String() string

String returns string representation of a span kind suitable for use as a value for `data.sdk.type` tag of an SDK span. By default all spans are intermediate unless they are explicitly set to be "entry" or "exit"

type SpanRecorder

type SpanRecorder interface {
	// Implementations must determine whether and where to store `span`.
	RecordSpan(span *spanS)
	// Flush forces sending any buffered finished spans
	Flush(context.Context) error
}

A SpanRecorder handles all of the `RawSpan` data generated via an associated `Tracer` (see `NewStandardTracer`) instance. It also names the containing process and provides access to a straightforward tag map.

type SpanReference added in v1.27.0

type SpanReference struct {
	TraceID string
	SpanID  string
}

SpanReference is a reference to a span, possibly belonging to another trace, that is relevant to the span context

type SpanSensitiveFunc deprecated added in v1.4.14

type SpanSensitiveFunc func(span ot.Span)

SpanSensitiveFunc is a function executed within a span context

Deprecated: use instana.ContextWithSpan() and instana.SpanFromContext() to inject and retrieve spans

type TraceReference added in v1.27.0

type TraceReference struct {
	TraceID  string `json:"t"`
	ParentID string `json:"p,omitempty"`
}

TraceReference is used to reference a parent span

type Tracer

type Tracer interface {
	opentracing.Tracer

	// Options gets the current tracer options
	Options() TracerOptions
	// Flush sends all finished spans to the agent
	Flush(context.Context) error
	// StartSpanWithOptions starts a span with the given options and return the span reference
	StartSpanWithOptions(string, ot.StartSpanOptions) ot.Span
}

Tracer extends the opentracing.Tracer interface

type TracerLogger added in v1.55.0

type TracerLogger interface {
	Tracer
	LeveledLogger
	LegacySensor() *Sensor
	SensorLogger
}

TracerLogger represents the Instana Go collector and is composed by a tracer, a logger and a reference to the legacy sensor.

var (
	C TracerLogger
)

func InitCollector added in v1.55.0

func InitCollector(opts *Options) TracerLogger

InitCollector creates a new Collector

type TracerOptions

type TracerOptions struct {
	// DropAllLogs turns log events on all spans into no-ops
	DropAllLogs bool
	// MaxLogsPerSpan limits the number of log records in a span (if set to a non-zero
	// value). If a span has more logs than this value, logs are dropped as
	// necessary
	MaxLogsPerSpan int
	// Secrets is a secrets matcher used to filter out sensitive data from HTTP requests, database
	// connection strings, etc. By default tracer does not filter any values. Package `secrets`
	// provides a set of secret matchers supported by the host agent configuration.
	//
	// See https://www.instana.com/docs/setup_and_manage/host_agent/configuration/#secrets for details
	Secrets Matcher
	// CollectableHTTPHeaders is a case-insensitive list of HTTP headers to be collected from HTTP requests and sent to the agent
	//
	// See https://www.instana.com/docs/setup_and_manage/host_agent/configuration/#capture-custom-http-headers for details
	CollectableHTTPHeaders []string
}

TracerOptions carry the tracer configuration

func DefaultTracerOptions added in v1.17.0

func DefaultTracerOptions() TracerOptions

DefaultTracerOptions returns the default set of options to configure a tracer

Directories

Path Synopsis
Package acceptor provides marshaling structs for Instana serverless acceptor API
Package acceptor provides marshaling structs for Instana serverless acceptor API
internal/pprof/profile
Package profile provides a representation of profile.proto and methods to encode/decode profiles in this format.
Package profile provides a representation of profile.proto and methods to encode/decode profiles in this format.
example
beego Module
echo Module
gin Module
httprouter Module
instrumentation
instaamqp Module
instaamqp091 Module
instaawssdk Module
instaawsv2 Module
instabeego Module
instacosmos Module
instaecho Module
instafiber Module
instagin Module
instagocb Module
instagorm Module
instagraphql Module
instagrpc Module
instalambda Module
instalogrus Module
instamongo Module
instamux Module
instapgx Module
instaredigo Module
instaredis Module
instasarama Module

Jump to

Keyboard shortcuts

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