trace

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2021 License: MIT Imports: 26 Imported by: 0

README

go.jinycoo.com/net/trace

项目简介
  1. 提供Trace的接口规范
  2. 提供 trace 对Tracer接口的实现,供业务接入使用
编译环境
  1. 请只用golang v1.7.x以上版本编译执行。
依赖包
编译执行
  1. 启动接入示例 if conf.Conf.Common.Trace { trace.Init(conf.Conf.tracer) }
  2. 配置参考 [tracer] proto = "unixgram" addr = "/var/run/dapper-collect/dapper-collect.sock" family = "account-service"
测试
  1. 执行当前目录下所有测试文件,测试所有功能
特别说明
  1. trace 需要在conf.common配置family 和设置trace = true 应用才能接入
trace sdk serviceName, operationName, tag 规范

注: serviceName 及之前的 family 字段, operationName 及之前的 title 字段

serviceName 使用 APP_ID 可以通过 caster 上 APP_ID 环境变量获取

全局 Tag
名称 类型 备注
hostname string 主机名
ip string caster上使用 POD_IP 环境变量,其他环境取第一个外网IP
zone string zone caster 使用 ZONE 环境变量 e.g. sh
region string region caster 使用 REGION 环境变量 e.g. region
HTTP

HTTP server && client 共同 tag

名称 类型 备注
http.method string GET、POST ...
http.url string http 完整 URL,包含 query
http.status_code int http 状态码

HTTP server

operationName 设置:

名称 类型 备注
span.kind string 固定值 server
component string 组件名称 e.g. library/net/http/jiny

HTTP client

operationName 设置:

  • 请求内部非 restful 的应用可以直接设置为 URL 的 path 部分
  • 请求的三方的服务或者 restful API operationName 可以直接设置为 HTTP:{Method} e.g. HTTP:GET
名称 类型 备注
span.kind string 固定值 client
component string 组件名称 e.g. pkg/net/http 或者 net/http
peer.service string 请求的服务APP_ID,例如请求 account-service 则应该设置为 main.account.account-service
_peer.sign string URL 的 path 部分不包含 query

注: peer.service 不知道可以不设置,_peer.sign 用于自定探测 peer.service

gRPC

gRPC server && client 共同 tag

gRPC server

operationName 设置:

名称 类型 备注
span.kind string 固定值 server
component string 固定值 gRPC

gRPC client

operationName 设置:

名称 类型 备注
span.kind string 固定值 client
component string 固定值 gRPC
peer.service string 请求的服务APP_ID,例如请求 account-service 则应该设置为 main.account.account-service
_peer.sign string gRPC FullMethod
goRPC

TODO

Memcache

TODO

Redis

TODO

MySQL

TODO

Databus

TODO

HBase

TODO

ElasticSearch

TODO

Documentation

Index

Constants

View Source
const (
	// 历史遗留的 key 不要轻易修改
	KeyTraceID       = "x1-et-id"
	KeyTraceSpanID   = "x1-et-spanid"
	KeyTraceParentID = "x1-et-parentid"
	KeyTraceSampled  = "x1-et-sampled"
	KeyTraceLevel    = "x1-et-lv"
	KeyTraceCaller   = "x1-et-user"
	// trace sdk should use jinycoo_trace_id to get trace info after this code be merged
	ETTraceID    = "et-trace-id"
	ETTraceDebug = "et-trace-debug"
)

Trace key

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

	// 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"

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

	// 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"

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

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

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

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

	// 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"

	// 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"

	// 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"

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

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

	// 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"

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

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

	// 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"

	// 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"

	// 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 (
	// The type or "kind" of an error (only for event="error" logs). E.g., "Exception", "OSError"
	// type string
	LogErrorKind = "error.kind"

	// 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"

	// 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"

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

	// 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

Variables

View Source
var (
	// ErrUnsupportedFormat occurs when the `format` passed to Tracer.Inject() or
	// Tracer.Extract() is not recognized by the Tracer implementation.
	ErrUnsupportedFormat = errors.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 = errors.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 = errors.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 = errors.New("trace: Invalid Inject/Extract carrier")

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

Functions

func Close

func Close() error

Close trace flush data.

func Init

func Init(cfg *Config)

func Inject

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

Inject takes the Trace instance and injects it for propagation within `carrier`. The actual type of `carrier` depends on the value of `format`.

func NewContext

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

NewContext new a trace context. NOTE: This method is not thread safe.

func SetGlobalTracer

func SetGlobalTracer(tracer Tracer)

SetGlobalTracer SetGlobalTracer

Types

type BuiltinFormat

type BuiltinFormat byte

BuiltinFormat is used to demarcate the values within package `trace` that are intended for use with the Tracer.Inject() and Tracer.Extract() methods.

const (
	// HTTPFormat represents Trace as HTTP header string pairs.
	//
	// the HTTPFormat format requires that the keys and values
	// be valid as HTTP headers as-is (i.e., character casing may be unstable
	// and special characters are disallowed in keys, values should be
	// URL-escaped, etc).
	//
	// the carrier must be a `http.Header`.
	HTTPFormat BuiltinFormat = iota
	// GRPCFormat represents Trace as gRPC metadata.
	//
	// the carrier must be a `google.golang.org/grpc/metadata.MD`.
	GRPCFormat
)

support format list

type Carrier

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

Carrier propagator must convert generic interface{} to something this implement Carrier interface, Trace can use Carrier to represents itself.

type Config

type Config struct {
	// Report network e.g. unixgram, tcp, udp
	Network string `dsn:"network"`
	// For TCP and UDP networks, the addr has the form "host:port".
	// For Unix networks, the address must be a file system path.
	Addr string `dsn:"address"`
	// DEPRECATED
	Proto string `dsn:"network"`
	// DEPRECATED
	Chan int `dsn:"query.chan,"`
	// Report timeout
	Timeout ctime.Duration `dsn:"query.timeout,200ms"`
	// DisableSample
	DisableSample bool `dsn:"query.disable_sample"`
	// probabilitySampling
	Probability float32 `dsn:"-"`
	// ProtocolVersion
	ProtocolVersion int32 `dsn:"query.protocol_version,2"`
}

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 Option

type Option func(*option)

Option dapper Option

func EnableDebug

func EnableDebug() Option

EnableDebug enable debug mode

type Tag

type Tag struct {
	Key   string
	Value interface{}
}

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 {
	// Fork fork a trace with client trace.
	Fork(serviceName, operationName string) Trace

	// Follow
	Follow(serviceName, operationName string) Trace

	// Finish when trace finish call it.
	Finish(err *error)

	// Adds a tag to the trace.
	//
	// If there is a pre-existing tag set for `key`, it is overwritten.
	//
	// Tag values can be numeric types, strings, or bools. The behavior of
	// other tag value types is undefined at the OpenTracing level. If a
	// tracing system does not know how to handle a particular value type, it
	// may ignore the tag, but shall not panic.
	// NOTE current only support legacy tag: TagAnnotation TagAddress TagComment
	// other will be ignore
	SetTag(tags ...Tag) Trace

	// LogFields is an efficient and type-checked way to record key:value
	// NOTE current unsupport
	SetLog(logs ...LogField) Trace

	// Visit visits the k-v pair in trace, calling fn for each.
	Visit(fn func(k, v string))

	// SetTitle reset trace title
	SetTitle(title string)
}

Trace trace common interface.

func Extract

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

Extract returns a Trace instance given `format` and `carrier`. return `ErrTraceNotFound` if trace not found.

func FromContext

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

FromContext returns the trace bound to the context, if any.

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 takes the Trace instance and injects it for
	// propagation within `carrier`. The actual type of `carrier` depends on
	// the value of `format`.
	Inject(t Trace, format interface{}, carrier interface{}) error
	// Extract returns a Trace instance given `format` and `carrier`.
	// return `ErrTraceNotFound` if trace not found.
	Extract(format interface{}, carrier interface{}) (Trace, error)
}

Tracer is a simple, thin interface for Trace creation and propagation.

func TracerFromEnvFlag

func TracerFromEnvFlag() (Tracer, error)

TracerFromEnvFlag new tracer from env and flag

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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