文档

通过SkyWalking上报Go应用数据

更新时间:

通过SkyWalking为应用埋点并上报链路数据至可观测链路 OpenTelemetry 版后,可观测链路 OpenTelemetry 版即可开始监控应用,您可以查看应用拓扑、调用链路、异常事务、慢事务和SQL分析等一系列监控数据。本文介绍如何使用SkyWalking Go Agent进行自动埋点并上报应用数据。

前提条件

获取接入点信息

  1. 登录可观测链路 OpenTelemetry 版控制台

  2. 在左侧导航栏单击集群配置,然后在右侧页面单击接入点信息页签。

  3. 在页面顶部选择需要接入的地域,然后在集群信息区域打开显示Token开关。

  4. 客户端采集工具区域单击SkyWalking

    在下方表格的相关信息列中,获取接入点信息。

    SkyWalking接入点信息

    说明

    如果应用部署于阿里云生产环境,则选择阿里云VPC网络接入点,否则选择公网接入点。

Agent选择

Go2Sky是SkyWalking官方旧版的SkyWalking Go探针,使用人数较多,但侵入较严重,因此官方推出了新版的skywalking-go探针,新版探针具有无侵入的特性。本文同时提供skywalking-go和Go2Sky两种探针接入流程,方便您将数据上报至可观测链路 OpenTelemetry 版控制台。

Go2Sky

  • 旧版SkyWalking Agent,在skywalking-go Agent正式发布后停止支持。

    根据官网页面显示,Go2Sky已被移到Retired,即不再维护。

  • 代码侵入较严重,每一个插件都要在项目中添加Hook。

  • 使用人数较多。

  • 支持的埋点库:

    展开查看支持的埋点库

    库名称

    监控安装方式

    sql

    go get -u github.com/SkyAPM/go2sky-plugins/sql

    dubbo-go

    go get -u github.com/SkyAPM/go2sky-plugins/dubbo-go

    gear

    go get -u github.com/SkyAPM/go2sky-plugins/gear

    gin

    go get -u github.com/SkyAPM/go2sky-plugins/gin/v2
    go get -u github.com/SkyAPM/go2sky-plugins/gin/v3

    go-restful

    go get -u github.com/SkyAPM/go2sky-plugins/go-restful

    gorm

    go get -u github.com/SkyAPM/go2sky-plugins/gorm

    http

    go get -u github.com/SkyAPM/go2sky

    go-kratos v2

    go get -u github.com/SkyAPM/go2sky-plugins/kratos

    logrus

    go get -u github.com/SkyAPM/go2sky-plugins/logrus

    go-micro(v3.5.0)

    go get -u github.com/SkyAPM/go2sky-plugins/micro

    mongo

    go get -u github.com/SkyAPM/go2sky-plugins/mongo

    go-resty(v2.2.0)

    go get -u github.com/SkyAPM/go2sky-plugins/resty

    zap(v1.16.0)

    go get -u github.com/SkyAPM/go2sky-plugins/zap

skywalking-go

  • 新版SkyWalking Agent,官方提供稳定支持。

  • 代码几乎无侵入。

  • 用法简单,只需要编译GoLang项目时通过-toolexec参数指定skywalking-go Agent。

  • 使用人数相对Go2Sky较少。

  • 支持的埋点库:

    展开查看支持的埋点库

    库名称

    监控安装方式

    sql

    无需安装。

    dubbo-go

    gear

    gin

    go-restful

    gorm

    http

    go-kratos v2

    logrus

    go-micro(v3.5.0)

    mongo

    go-resty(v2.2.0)

    zap(v1.16.0)

推荐Agent

建议您使用新版skywalking-go探针,优势如下:

  • 使用简便:skywalking-go使用更简单,您只需要通过简短的步骤即可完成接入和自动埋点。Skywalking-go是无侵入式探针,而Go2Sky在使用插件时需要手动添加Hook钩子。

  • 社区支持:官方将取消对Go2Sky的继续支持,也不再接受关于Go2Sky的PR。

  • 插件生态:官方将会持续将Go2Sky的插件移植到skywalking-go。目前,skywalking-go相比Go2Sky多了对gRPC框架的埋点。

示例Demo

示例Demo仓库地址:SkyWalking Demo

通过skywalking-go探针上报

  1. 下载skywalking-go Agent。

  2. 构建Agent。

    cd skywalking-go && make build
  3. 在skywalking-go/bin路径下生成可执行文件

    不同的操作系统对应的可执行文件不同。例如,mac系统需选择skywalking-go-agent--darwin-amd64。

    image.png

  4. 打开Go项目,在main package中导入skywalking module。

    方式一

    package main
    
    import (
    	_ "github.com/apache/skywalking-go"
    )

    方式二

    skywalking-go/bin/skywalking-go-agent--darwin-amd64 -inject path/to/your-project
  5. 配置config.yaml文件。

    您可以参考示例Demo的skywalking-go/tools/go-agent/config/config.default.yaml文件修改。

    展开查看config.default.yaml文件示例

    agent:
      # Service name is showed in UI.
      service_name: ${SW_AGENT_NAME:Your_ApplicationName}
      # To obtain the environment variable key for the instance name, if it cannot be obtained, an instance name will be automatically generated.
      instance_env_name: SW_AGENT_INSTANCE_NAME
      # Sampling rate of tracing data, which is a floating-point value that must be between 0 and 1.
      sampler: ${SW_AGENT_SAMPLE:1}
      meter:
        # The interval of collecting metrics, in seconds.
        collect_interval: ${SW_AGENT_METER_COLLECT_INTERVAL:20}
    
    reporter:
      grpc:
        # The gRPC server address of the backend service.
        backend_service: ${SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE:127.0.0.1:11800}
        # The maximum count of segment for reporting tracing data.
        max_send_queue: ${SW_AGENT_REPORTER_GRPC_MAX_SEND_QUEUE:5000}
        # The interval(s) of checking service and backend service
        check_interval: ${SW_AGENT_REPORTER_GRPC_CHECK_INTERVAL:20}
        # The authentication string for communicate with backend.
        authentication: ${SW_AGENT_REPORTER_GRPC_AUTHENTICATION:}
        # The interval(s) of fetching dynamic configuration from backend.
        cds_fetch_interval: ${SW_AGENT_REPORTER_GRPC_CDS_FETCH_INTERVAL:20}
        tls:
          # Whether to enable TLS with backend.
          enable: ${SW_AGENT_REPORTER_GRPC_TLS_ENABLE:false}
          # The file path of ca.crt. The config only works when opening the TLS switch.
          ca_path: ${SW_AGENT_REPORTER_GRPC_TLS_CA_PATH:}
          # The file path of client.pem. The config only works when mTLS.
          client_key_path: ${SW_AGENT_REPORTER_GRPC_TLS_CLIENT_KEY_PATH:}
          # The file path of client.crt. The config only works when mTLS.
          client_cert_chain_path: ${SW_AGENT_REPORTER_GRPC_TLS_CLIENT_CERT_CHAIN_PATH:}
          # Controls whether a client verifies the server's certificate chain and host name.
          insecure_skip_verify: ${SW_AGENT_REPORTER_GRPC_TLS_INSECURE_SKIP_VERIFY:false}
    
    log:
      # The type determines which logging type is currently used by the system.
      # The Go agent wourld use this log type to generate custom logs. It supports: "auto", "logrus", or "zap".
      # auto: Automatically identifies the source of the log.
      #       If logrus is present in the project, it wourld automatically use logrus.
      #       If zap has been initialized in the project, it would use the zap framework.
      #       By default, it would use std errors to output log content.
      # logrus: Specifies that the Agent should use the logrus framework.
      # zap: Specifies that the Agent should use the zap framework.
      # The system must have already been initialized through methods such as "zap.New", "zap.NewProduction", etc.
      type: ${SW_AGENT_LOG_TYPE:auto}
      tracing:
        # Whether to automatically integrate Tracing information into the logs.
        enable: ${SW_AGENT_LOG_TRACING_ENABLE:true}
        # If tracing information is enabled, the tracing information would be stored in the current Key in each log.
        key: ${SW_AGENT_LOG_TRACING_KEY:SW_CTX}
      reporter:
        # Whether to upload logs to the backend.
        enable: ${SW_AGENT_LOG_REPORTER_ENABLE:true}
        # The fields name list that needs to added to the label of the log.(multiple split by ",")
        label_keys: ${SW_AGENT_LOG_REPORTER_LABEL_KEYS:}
    
    plugin:
      # List the names of excluded plugins, multiple plugin names should be splitted by ","
      # NOTE: This parameter only takes effect during the compilation phase.
      excluded: ${SW_AGENT_PLUGIN_EXCLUDES:}
      config:
        http:
          # Collect the parameters of the HTTP request on the server side
          server_collect_parameters: ${SW_AGENT_PLUGIN_CONFIG_HTTP_SERVER_COLLECT_PARAMETERS:false}
        mongo:
          # Collect the statement of the MongoDB request
          collect_statement: ${SW_AGENT_PLUGIN_CONFIG_MONGO_COLLECT_STATEMENT:false}
        sql:
          # Collect the parameter of the SQL request
          collect_parameter: ${SW_AGENT_PLUGIN_CONFIG_SQL_COLLECT_PARAMETER:false}
    

    设置参数有以下两种方式,例如,如果要配置service_name,配置方法如下:

    方式一(推荐):直接在config.yaml中添加参数

    agent:
      service_name: ${SW_AGENT_NAME:<your_service_name>}

    方式二:配置系统环境变量

    export SW_AGENT_NAME=<your_service_name>

    接入可观测链路 OpenTelemetry 版控制台需要设置以下参数:

    • service_name: ${SW_AGENT_NAME:Your_ApplicationName}:服务名称。

    • backend_service: ${SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE:127.0.0.1:11800}:接入点的Endpoint。

    • authentication: ${SW_AGENT_REPORTER_GRPC_AUTHENTICATION:}:接入点鉴权Token。

    skywalking-go Agent默认对所有的插件自动埋点,若需要移除特定插件,可以设置excluded参数,例如:

    # 如果想要关闭sql plugin
    plugin:
      excluded: ${SW_AGENT_PLUGIN_EXCLUDES:sql}
    
    # 如果想同时关闭多个plugin,使用,分隔
    plugin:
      excluded: ${SW_AGENT_PLUGIN_EXCLUDES:sql,gorm}
  6. 重新构建项目。

    # 需要使用-toolexec
    sudo go build -toolexec "path/to/skywalking-go-agent -config path/to/config.yaml" -a
    • path/to/skywalking-go-agent:上文步骤1可执行文件的绝对路径。

    • path/to/config.yaml:skywalking-go Agent的参数配置文件的绝对路径。

  7. 启动项目。此时SkyWalking数据将会上报至可观测链路 OpenTelemetry 版控制台。

参考信息

skywalking-go探针的部分属性列表,NULL表示默认值未设置:

环境变量

描述

默认值

SW_AGENT_NAME

服务名称。

NULL

SW_AGENT_INSTANCE_NAME

服务实例名称。

自动生成

SW_AGENT_SAMPLE

采样率,取值在0和1之间。

1

SW_AGENT_REPORTER_GRPC_BACKEND_SERVICE

监控数据通过gRPC上报的服务端Endpoint。

127.0.0.1:11800

SW_AGENT_REPORTER_GRPC_AUTHENTICATION

监控数据通过gRPC上报的服务端的鉴权Token。

NULL

SW_AGENT_PLUGIN_EXCLUDES

指定移除的插件。

NULL

通过Go2Sky探针上报

  1. Go2Sky同时支持配置参数硬编码到项目或通过环境变量自动配置两种方法。

    配置参数硬编码

    ### 使用reporter.WithParameter()导入参数
    report, err := reporter.NewGRPCReporter(
        <your-backend-server-address>,
        reporter.WithAuthentication(<your-auth-token>))

    环境变量自动配置

    ### 目前go2sky支持从环境变量获取以下参数
    SW_AGENT_AUTHENTICATION
    SW_AGENT_LAYER
    SW_AGENT_COLLECTOR_HEARTBEAT_PERIOD
    SW_AGENT_COLLECTOR_GET_AGENT_DYNAMIC_CONFIG_INTERVAL
    SW_AGENT_COLLECTOR_BACKEND_SERVICES
    SW_AGENT_COLLECTOR_MAX_SEND_QUEUE_SIZE
    SW_AGENT_PROCESS_STATUS_HOOK_ENABLE
    SW_AGENT_PROCESS_LABELS
    
    ### 配置环境变量,以macOS为例
    # 方法1:写入环境变量配置文件(持久化)
    vim ~/.bash_profile
    export SW_AGENT_COLLECTOR_BACKEND_SERVICES=<your-collector-address>
    source ~/.bash_profile
    # 方法2:打开终端,命令行配置(临时生效,打开新的终端失效)
    export SW_AGENT_COLLECTOR_BACKEND_SERVICES=<your-collector-address>
  2. 配置ServiceName,用于识别具体的应用。

    ServiceName := <your-service-name>
    tracer, err := go2sky.NewTracer(ServiceName, go2sky.WithReporter(report))
  3. 添加Go2Sky-Plugin Hook。

    Go2Sky开发了众多库的插件,但是需要在项目源代码中添加埋点。如何添加埋点请参见Go2Sky-Plugins的Github仓库。在每个插件的plugin文件夹下,README.md文件给了简单的使用示例。

    以gin框架为例:

    1. 进入/gin文件夹,查看/gin/v3/README.md文件。

    2. 添加Middleware的Hook:v3.Middleware(r, tracer)

      package main
      
      import (
      	"log"
      
      	"github.com/SkyAPM/go2sky"
      	v3 "github.com/SkyAPM/go2sky-plugins/gin/v3"
      	"github.com/SkyAPM/go2sky/reporter"
      	"github.com/gin-gonic/gin"
      )
      
      func main() {
      	// Use gRPC reporter for production
      	re, err := reporter.NewLogReporter()
      	if err != nil {
      		log.Fatalf("new reporter error %v \n", err)
      	}
      	defer re.Close()
      
      	tracer, err := go2sky.NewTracer("gin-server", go2sky.WithReporter(re))
      	if err != nil {
      		log.Fatalf("create tracer error %v \n", err)
      	}
      
      	gin.SetMode(gin.ReleaseMode)
      	r := gin.New()
      
      	//Use go2sky middleware with tracing
      	r.Use(v3.Middleware(r, tracer))
      
      	// do something
      }
  4. 重新启动应用。

参考信息

Go2Sky的Agent属性配置表,NULL表示默认值未设置:

环境变量

描述

默认值

SW_AGENT_NAME

Go服务的名称。

NULL

SW_AGENT_LAYER

Instance belong layer name which define in the backend

实例所属的layer名称。

NULL

SW_AGENT_INSTANCE_NAME

Go服务的实例名称。

随机生成

SW_AGENT_SAMPLE

采样率,1表示全量采集。

1

SW_AGENT_COLLECTOR_BACKEND_SERVICES

Agent数据上报的服务端地址。

NULL

SW_AGENT_AUTHENTICATION

Agent数据上报的服务端的鉴权令牌。

NULL

SW_AGENT_COLLECTOR_HEARTBEAT_PERIOD

Agent心跳上报周期,单位:s。

20

SW_AGENT_COLLECTOR_GET_AGENT_DYNAMIC_CONFIG_INTERVAL

动态获取Agent配置的时间间隔,单位:s。

20

SW_AGENT_COLLECTOR_MAX_SEND_QUEUE_SIZE

发送跨度Span的队列Buffer长度。

30000

SW_AGENT_PROCESS_STATUS_HOOK_ENABLE

启用进程状态Hook功能。

False

SW_AGENT_PROCESS_LABELS

进程标签,多个标签用英文半角逗号(,)分隔。

NULL

常见问题

  • 使用skywalking-go时报错如下:

    image.png

    如果使用inject方式报错,您可以通过import在main package中导入skywalking module。

  • 跨进程调用时,为什么通过Go2Sky上报可观测链路 OpenTelemetry 版控制台无法显示正确的调用链?

    全链路追踪通过TraceId将整个链路串联起来,而TraceId通过HTTP请求携带传递。如果调用链不正确,说明TraceId没有正确传递,需要设置合理的Span埋点。

    通过合理使用下面两个重要的接口,可以将跨进程的调用链正确的串联起来:

    • CreateEntrySpan:入口Span,可以通过该接口从HTTP请求中提取得到链路追踪上下文(包含TraceId)。

    • CreateExitSpan:出口Span,可以通过该接口向HTTP请求注入链路追踪上下文(包含TraceId)。

    // 进程内,使用CreateLocalSpan创建一个跨度(Span)。
    span, ctx, err := tracer.CreateLocalSpan(context.Background())
    subSpan, newCtx, err := tracer.CreateLocalSpan(ctx)
    
    // 跨进程,使用入口Span从CreateEntrySpan从Http请求中提取上下文,使用出口Span向CreateExitSpan向Http请求中注入上下文。
    span, ctx, err := tracer.CreateEntrySpan(r.Context(), "/api/login", func(key string) (string, error) {
        return r.Header.Get(key), nil
    })
    span, err := tracer.CreateExitSpan(req.Context(), "/service/validate", "tomcat-service:8080", func(key, value string) error {
    		req.Header.Set(key, value)
    		return nil
    })

    跨进程的项目,不同进程之间需要传递TraceId才能将调用链串联起来,所以需要用到上面的接口将上下文注入到HTTP请求中随着请求在进程间传递。

相关文档

  • 本页导读 (1)
文档反馈