trace

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2022 License: MPL-2.0 Imports: 23 Imported by: 3

README

背景

当代的互联网的服务,通常都是用复杂的、大规模分布式集群来实现的。互联网应用构建在不同的软件模块集上,这些软件模块,有可能是由不同的团队开发、可能使用不同的编程语言来实现、有可能布在了几千台服务器,横跨多个不同的数据中心。因此,就需要一些可以帮助理解系统行为、用于分析性能问题的工具。

概览

  • trace基于opentracing语义
  • 全链路支持(gRPC/HTTP/MySQL/Redis/Memcached等)

参考文档

opentracing
dapper

使用

本身不提供整套trace数据方案,但在report.go内声明了repoter接口,可以简单的集成现有开源系统,比如:zipkinjaeger

Documentation

Index

Constants

View Source
const (
	// TagComponent The software package, framework, library, or module that generated the associated Span.
	// E.g., "gRpc", "django", "JDBI".
	// type string
	TagComponent = "component"

	// TagDBInstance Database instance name.
	// E.g., In java, if the jdbc.url="jdbc:mysql://127.0.0.1:3306/customers", the instance name is "customers".
	// type string
	TagDBInstance = "db.instance"

	// TagDBStatement A database statement for the given database type.
	// E.g., for db.type="sql", "SELECT * FROM fc_table"; for db.type="redis", "SET mykey 'WuValue'".
	TagDBStatement = "db.statement"

	// TagDBType Database type. For any SQL database, "sql". For others, the lower-case database category,
	// e.g. "cassandra", "HBase", or "redis".
	// type string
	TagDBType = "db.type"

	// TagDBUser Username for accessing database. E.g., "readonly_user" or "reporting_user"
	// type string
	TagDBUser = "db.user"

	// TagError true if and only if the application considers the operation represented by the Span to have failed
	// type bool
	TagError = "error"

	// TagHTTPMethod HTTP method of the request for the associated Span. E.g., "GET", "POST"
	// type string
	TagHTTPMethod = "http.method"

	// TagHTTPStatusCode HTTP response status code for the associated Span. E.g., 200, 503, 404
	// type integer
	TagHTTPStatusCode = "http.status_code"

	// TagHttpURL URL of the request being handled in this segment of the trace, in standard URI format.
	// E.g., "https://domain.net/path/to?resource=here"
	// type string
	TagHttpURL = "http.url"

	// TagMessageBusDestination An address at which messages can be exchanged.
	// E.g. A Kafka record has an associated "topic name" that can be extracted by the instrumented producer or consumer and stored using this tag.
	// type string
	TagMessageBusDestination = "message_bus.destination"

	// TagPeerAddress Remote "address", suitable for use in a networking client library.
	// This may be a "ip:port", a bare "hostname", a FQDN, or even a JDBC substring like "mysql://prod-db:3306"
	// type string
	TagPeerAddress = "peer.address"

	// TagPeerHostname	Remote hostname. E.g., "opentracing.io", "internal.dns.name"
	// type string
	TagPeerHostname = "peer.hostname"

	// TagPeerIPv4 Remote IPv4 address as a .-separated tuple. E.g., "127.0.0.1"
	// type string
	TagPeerIPv4 = "peer.ipv4"

	// TagPeerIPv6 Remote IPv6 address as a string of colon-separated 4-char hex tuples.
	// E.g., "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
	// type string
	TagPeerIPv6 = "peer.ipv6"

	// TagPeerPort Remote port. E.g., 80
	// type integer
	TagPeerPort = "peer.port"

	// TagPeerService Remote service name (for some unspecified definition of "service").
	// E.g., "elasticsearch", "a_custom_microservice", "memcache"
	// type string
	TagPeerService = "peer.service"

	// TagSamplingPriority If greater than 0, a hint to the Tracer to do its best to capture the trace.
	// If 0, a hint to the trace to not-capture the trace. If absent, the Tracer should use its default sampling mechanism.
	// type string
	TagSamplingPriority = "sampling.priority"

	// TagSpanKind Either "client" or "server" for the appropriate roles in an RPC,
	// and "producer" or "consumer" for the appropriate roles in a messaging scenario.
	// type string
	TagSpanKind = "span.kind"

	// TagAnnotation legacy tag
	TagAnnotation = "legacy.annotation"
	TagAddress    = "legacy.address"
	TagComment    = "legacy.comment"
)

Standard Span tags https://github.com/opentracing/specification/blob/master/semantic_conventions.md#span-tags-table

View Source
const (
	// LogErrorKind The type or "kind" of an error (only for event="error" logs).
	// E.g., "Exception", "OSError" type string
	LogErrorKind = "error.kind"

	// LogErrorObject For languages that support such a thing (e.g., Java, Python), the actual Throwable/Exception/Error object instance itself.
	// E.g., A java.lang.UnsupportedOperationException instance, a python exceptions.NameError instance type string
	LogErrorObject = "error.object"

	// LogEvent A stable identifier for some notable moment in the lifetime of a Span.
	// For instance, a mutex lock acquisition or release or the sorts of lifetime events in a browser page load described in the Performance.timing specification.
	// E.g., from Zipkin, "cs", "sr", "ss", or "cr". Or, more generally, "initialized" or "timed out". For errors, "error" type string
	LogEvent = "event"

	// LogMessage A concise, human-readable, one-line message explaining the event.
	// E.g., "Could not connect to backend", "Cache invalidation succeeded" type string
	LogMessage = "message"

	// LogStack A stack trace in platform-conventional format; may or may not pertain to an error.
	// E.g., "File \"example.py\", line 7, in \<module\>\ncaller()\nFile \"example.py\", line 5, in caller\ncallee()\nFile \"example.py\", line 2, in callee\nraise Exception(\"Yikes\")\n" type string
	LogStack = "stack"
)

Standard log tags

View Source
const (
	// FosTraceID 跟踪键
	FosTraceID    = "fos-trace-id"
	FosTraceDebug = "fos-trace-debug"

	// HTTPFormat 将Trace表示为HTTP标头字符串对.
	// HTTPFormat格式要求键和值按原样作为HTTP标头有效(即,字符大小写可能不稳定,并且键中不允许使用特殊字符,值应转义URL,等等).
	// 载体必须是"http.Header".
	HTTPFormat BuiltinFormat = iota

	// GRPCFormat 承运人必须是`google.golang.org/grpc/metadata.MD`.
	GRPCFormat
)

Variables

View Source
var (
	// ErrUnsupportedFormat occurs when the `format` passed to Tracer.Inject() or
	// Tracer.Extract() is not recognized by the Tracer implementation.
	ErrUnsupportedFormat = errs.New("trace: Unknown or unsupported Inject/Extract format")

	// ErrTraceNotFound occurs when the `carrier` passed to
	// Tracer.Extract() is valid and uncorrupted but has insufficient
	// information to extract a Trace.
	ErrTraceNotFound = errs.New("trace: Trace not found in Extract carrier")

	// ErrInvalidTrace errors occur when Tracer.Inject() is asked to
	// operate on a Trace which it is not prepared to handle (for
	// example, since it was created by a different tracer implementation).
	ErrInvalidTrace = errs.New("trace: Trace type incompatible with tracer")

	// ErrInvalidCarrier errors occur when Tracer.Inject() or Tracer.Extract()
	// implementations expect a different type of `carrier` than they are
	// given.
	ErrInvalidCarrier = errs.New("trace: Invalid Inject/Extract carrier")

	// ErrTraceCorrupted occurs when the `carrier` passed to
	// Tracer.Extract() is of the expected type but is corrupted.
	ErrTraceCorrupted = errs.New("trace: Trace data corrupted in Extract carrier")
)

Functions

func Close

func Close() error

Close trace flush data.

func Init

func Init(serviceName string, tags []Tag, cfg *Config)

Init init trace report.

func Inject

func Inject(t Trace, format interface{}, carrier interface{}) error

Inject 接收Trace实例,并将其注入以在`carrier`中传播.载体的实际类型取决于format的值.

func NewContext

func NewContext(ctx context.Context, t Trace) context.Context

NewContext 新的跟踪上下文.注意:此方法不是线程安全的.

func SetGlobalTracer

func SetGlobalTracer(tracer Tracer)

SetGlobalTracer SetGlobalTracer

Types

type BuiltinFormat

type BuiltinFormat byte

BuiltinFormat 用于在"trace"包中划分与Tracer.Inject()和Tracer.Extract()方法一起使用的值。

type Carrier

type Carrier interface {
	Set(key, val string)
	Get(key string) string
}

Carrier 传播者必须将通用接口{}转换为此实现Carrier接口的东西,Trace可以使用Carrier表示自己。

type Config

type Config struct {
	// 报告网络,例如:Unix,TCP,UDP
	Network string `json:"network"`
	// 对于TCP和UDP网络,地址的格式为“ host:port”。
	// 对于Unix网络,该地址必须是文件系统路径。
	Addr string `json:"address"`
	// 报告超时
	Timeout utils.Duration `json:"timeout"`
	// DisableSample
	DisableSample bool `json:"disable_sample"`
	// ProtocolVersion
	ProtocolVersion int32 `json:"protocol_version"`
	// Probability probability sampling
	Probability float32
}

Config config.

type LogField

type LogField struct {
	Key   string
	Value string
}

LogField LogField

func Log

func Log(key string, val string) LogField

Log new log.

type MockSpan

type MockSpan struct {
	*MockTrace
	OperationName string
	FinishErr     error
	Finished      bool
	Tags          []Tag
	Logs          []LogField
}

MockSpan .

func (*MockSpan) Finish

func (m *MockSpan) Finish(err *error)

func (*MockSpan) Follow

func (m *MockSpan) Follow(serviceName string, operationName string) Trace

func (*MockSpan) Fork

func (m *MockSpan) Fork(serviceName string, operationName string) Trace

func (*MockSpan) SetLog

func (m *MockSpan) SetLog(logs ...LogField) Trace

func (*MockSpan) SetTag

func (m *MockSpan) SetTag(tags ...Tag) Trace

func (*MockSpan) SetTitle

func (m *MockSpan) SetTitle(title string)

func (*MockSpan) TraceId

func (m *MockSpan) TraceId() string

func (*MockSpan) Visit

func (m *MockSpan) Visit(fn func(k, v string))

type MockTrace

type MockTrace struct {
	Spans []*MockSpan
}

MockTrace .

func (*MockTrace) Extract

func (m *MockTrace) Extract(format interface{}, carrier interface{}) (Trace, error)

Extract .

func (*MockTrace) Inject

func (m *MockTrace) Inject(t Trace, format interface{}, carrier interface{}) error

Inject .

func (*MockTrace) New

func (m *MockTrace) New(operationName string, opts ...Option) Trace

New .

type Option

type Option func(*option)

Option dapper Option

func EnableDebug

func EnableDebug() Option

EnableDebug enable debug mode

type Span

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

Span is a trace span.

func (*Span) Context

func (s *Span) Context() spanContext

func (*Span) Duration

func (s *Span) Duration() time.Duration

func (*Span) Finish

func (s *Span) Finish(perr *error)

func (*Span) Follow

func (s *Span) Follow(serviceName, operationName string) Trace

func (*Span) Fork

func (s *Span) Fork(serviceName, operationName string) Trace

func (*Span) Logs

func (s *Span) Logs() []*protoGen.Log

func (*Span) OperationName

func (s *Span) OperationName() string

func (*Span) ServiceName

func (s *Span) ServiceName() string

func (*Span) SetLog

func (s *Span) SetLog(logs ...LogField) Trace

SetLog LogFields是一种有效且经过类型检查的方式来记录key:value 注意:当前不支持

func (*Span) SetTag

func (s *Span) SetTag(tags ...Tag) Trace

func (*Span) SetTitle

func (s *Span) SetTitle(operationName string)

SetTitle reset trace title

func (*Span) StartTime

func (s *Span) StartTime() time.Time

func (*Span) String

func (s *Span) String() string

func (*Span) Tags

func (s *Span) Tags() []Tag

func (*Span) TraceId

func (s *Span) TraceId() string

func (*Span) Visit

func (s *Span) Visit(fn func(k, v string))

Visit visits the k-v pair in trace, calling fn for each.

type Tag

type Tag struct {
	Key   string      `json:"key"`
	Value interface{} `json:"value"`
}

Tag interface

func Bool

func Bool(key string, val bool) Tag

Bool new tagBool NOTE: use TagBool

func Int

func Int(key string, val int) Tag

Int new tag Int. NOTE: use TagInt

func String

func String(key string, val string) Tag

String new tag String. NOTE: use TagString

func TagBool

func TagBool(key string, val bool) Tag

TagBool new bool tag

func TagFloat32

func TagFloat32(key string, val float32) Tag

TagFloat32 new float64 tag

func TagFloat64

func TagFloat64(key string, val float64) Tag

TagFloat64 new float64 tag

func TagInt

func TagInt(key string, val int) Tag

TagInt new int tag

func TagInt64

func TagInt64(key string, val int64) Tag

TagInt64 new int64 tag.

func TagString

func TagString(key string, val string) Tag

TagString new string tag.

type Trace

type Trace interface {
	// TraceId 返回当前跟踪ID.
	TraceId() string

	// Fork 用客户端跟踪派生一个跟踪。
	Fork(serviceName, operationName string) Trace

	Follow(serviceName, operationName string) Trace

	// Finish 当跟踪完成时调用它.
	Finish(err *error)

	// SetTag 添加跟踪标签。
	//
	// 如果为`key`设置了预先存在的标签,则该标签将被覆盖。
	//
	// 标记值可以是数字类型,字符串或布尔值.
	// 其他标记值类型的行为在OpenTracing级别上未定义。
	// 如果跟踪系统不知道如何处理特定的值类型,则可以忽略该标签,但不要惊慌。
	// 注意当前仅支持旧标签:TagAnnotation TagAddress TagComment other将被忽略
	SetTag(tags ...Tag) Trace

	//SetLog  LogFields是一种有效且经过类型检查的方式来记录key:value 注意当前不支持
	SetLog(logs ...LogField) Trace

	// Visit 跟踪访问k-v对,并分别为fn.
	Visit(fn func(k, v string))

	// SetTitle 重置跟踪标题
	SetTitle(title string)
}

Trace trace common interface.

func Extract

func Extract(format interface{}, carrier interface{}) (Trace, error)

Extract 返回给定`format`和`carrier'的Trace实例. 如果未找到跟踪,则返回`ErrTraceNotFound`.

func FromContext

func FromContext(ctx context.Context) (t Trace, ok bool)

FromContext 返回绑定到上下文的跟踪(如果有).

func New

func New(operationName string, opts ...Option) Trace

New trace instance with given operationName.

type Tracer

type Tracer interface {
	// New trace instance with given title.
	New(operationName string, opts ...Option) Trace
	// Inject 接收Trace实例,并注入它以便在`carrier`中传播.
	// 载体的实际类型取决于格式的值.
	Inject(t Trace, format interface{}, carrier interface{}) error
	// Extract 返回给定`format`和`carrier`的Trace实例.
	// 如果未找到跟踪,则返回`ErrTraceNotFound`.
	Extract(format interface{}, carrier interface{}) (Trace, error)
}

Tracer 是用于跟踪创建和传播的简单,轻界面.

func NewTracer

func NewTracer(serviceName string, tags []Tag, report reporter, disableSample bool) Tracer

NewTracer new a tracer.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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