从 Go(预览版)收集分布式跟踪Collect distributed traces from Go (Preview)

Application Insights 现在支持通过与 OpenCensus 和我们新的本地转发器集成来对 Go 应用程序进行分布式跟踪。Application Insights now supports distributed tracing of Go applications through integration with OpenCensus and our new local forwarder. 本文将逐步介绍设置 OpenCensus for Go 并将跟踪数据提供给 Application Insights 的过程。This article will walk you step-by-step through the process of setting up OpenCensus for Go and getting your trace data to Application Insights.

先决条件Prerequisites

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a trial account before you begin.

登录到 Azure 门户Sign in to the Azure portal

登录到 Azure 门户Sign in to the Azure portal.

创建 Application Insights 资源Create Application Insights resource

首先,你需要创建一个 Application Insights 资源,该资源将生成一个检测密钥 (ikey)。First you have to create an Application Insights resource which will generate an instrumentation key (ikey). 然后使用 ikey 配置本地转发器,以将 OpenCensus 检测应用程序中的分布式跟踪发送到 Application Insights。The ikey is then used to configure the local forwarder to send distributed traces from your OpenCensus instrumented application, to Application Insights.

  1. 选择“创建资源” > “开发人员工具” > “Application Insights” 。Select Create a resource > Developer Tools > Application Insights.

    添加 Application Insights 资源

备注

如果这是你首次创建 Application Insights 资源,可以通过访问创建 Application Insights 资源一文来了解更多信息。If this is your first time creating an Application Insights resource you can learn more by visiting the Create an Application Insights Resource article.

此时会显示配置对话框,请使用下表填写输入字段。A configuration box appears; use the following table to fill out the input fields.

| <span data-ttu-id="cfadf-120">设置</span><span class="sxs-lookup"><span data-stu-id="cfadf-120">Settings</span></span>        | <span data-ttu-id="cfadf-121">Value</span><span class="sxs-lookup"><span data-stu-id="cfadf-121">Value</span></span>           | <span data-ttu-id="cfadf-122">说明</span><span class="sxs-lookup"><span data-stu-id="cfadf-122">Description</span></span>  |

| ------------- |:-------------|:-----| | 名称Name | 全局唯一值Globally Unique Value | 标识所监视的应用的名称Name that identifies the app you are monitoring | | 资源组Resource Group | MyResourceGroupmyResourceGroup | 用于托管 App Insights 数据的新资源组的名称Name for the new resource group to host App Insights data | | 位置Location | 中国北部China North| 选择离你近的位置或离托管应用的位置近的位置Choose a location near you, or near where your app is hosted |

  1. 单击创建Click Create.

配置本地转发器Configure local forwarder

  1. 选择“概述” > “概要” > 复制应用程序的检测密钥Select Overview > Essentials > Copy your application's Instrumentation Key.

    检测密钥的屏幕截图

  2. 编辑 LocalForwarder.config 文件并添加检测密钥。Edit your LocalForwarder.config file and add your instrumentation key. 如果已按照先决条件中的说明操作,则该文件位于 C:\LF-WindowsServiceHostIf you followed the instructions in the pre-requisite the file is located at C:\LF-WindowsServiceHost

      <OpenCensusToApplicationInsights>
        <!--
          Instrumentation key to track telemetry to.
          -->
        <InstrumentationKey>{enter-instrumentation-key}</InstrumentationKey>
      </OpenCensusToApplicationInsights>
    
      <!-- Describes aspects of processing Application Insights telemetry-->
      <ApplicationInsights>
        <LiveMetricsStreamInstrumentationKey>{enter-instrumentation-key}</LiveMetricsStreamInstrumentationKey>
      </ApplicationInsights>
    </LocalForwarderConfiguration>
    
  3. 重启应用程序本地转发器服务。Restart the application Local Forwarder service.

OpenCensus Go 包OpenCensus Go packages

  1. 从命令行安装用于 Go 的 Open Census 包:Install the Open Census packages for Go from the command line:

    go get -u go.opencensus.io
    go get -u contrib.go.opencensus.io/exporter/ocagent
    
  2. 将以下代码添加到 .go 文件,然后生成并运行。Add the following code to a .go file and then build and run. (此示例源自官方 OpenCensus 指南,其中添加了有助于与本地转发器集成的代码)(This example is derived from the official OpenCensus guidance with added code that facilitates the integration with the local forwarder)

       // Copyright 2018, OpenCensus Authors
       //
       // Licensed under the Apache License, Version 2.0 (the "License");
       // you may not use this file except in compliance with the License.
       // You may obtain a copy of the License at
       //
       //     https://www.apache.org/licenses/LICENSE-2.0
       //
       // Unless required by applicable law or agreed to in writing, software
       // distributed under the License is distributed on an "AS IS" BASIS,
       // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       // See the License for the specific language governing permissions and
       // limitations under the License.
       package main
    
       import (
    
           "bytes"
           "fmt"
           "log"
           "net/http"
           os "os"
    
           ocagent "contrib.go.opencensus.io/exporter/ocagent"
           "go.opencensus.io/plugin/ochttp"
           "go.opencensus.io/plugin/ochttp/propagation/tracecontext"
           "go.opencensus.io/trace"
    
       )
    
       func main() {
           // Register stats and trace exporters to export the collected data.
           serviceName := os.Getenv("SERVICE_NAME")
           if len(serviceName) == 0 {
               serviceName = "go-app"
           }
           fmt.Printf(serviceName)
           agentEndpoint := os.Getenv("OCAGENT_TRACE_EXPORTER_ENDPOINT")
    
           if len(agentEndpoint) == 0 {
               agentEndpoint = fmt.Sprintf("%s:%d", ocagent.DefaultAgentHost, ocagent.DefaultAgentPort)
           }
    
           fmt.Printf(agentEndpoint)
           exporter, err := ocagent.NewExporter(ocagent.WithInsecure(), ocagent.WithServiceName(serviceName), ocagent.WithAddress(agentEndpoint))
    
           if err != nil {
               log.Printf("Failed to create the agent exporter: %v", err)
           }
    
           trace.RegisterExporter(exporter)
    
           trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
    
           client := &http.Client{Transport: &ochttp.Transport{Propagation: &tracecontext.HTTPFormat{}}}
    
           http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
               fmt.Fprintf(w, "hello world")
    
               var jsonStr = []byte(`[ { "url": "http://blank.org", "arguments": [] } ]`)
               r, _ := http.NewRequest("POST", "http://blank.org", bytes.NewBuffer(jsonStr))
               r.Header.Set("Content-Type", "application/json")
    
               // Propagate the trace header info in the outgoing requests.
               r = r.WithContext(req.Context())
               resp, err := client.Do(r)
               if err != nil {
                   log.Println(err)
               } else {
                   // TODO: handle response
                   resp.Body.Close()
               }
           })
    
           http.HandleFunc("/call_blank", func(w http.ResponseWriter, req *http.Request) {
               fmt.Fprintf(w, "hello world")
    
               r, _ := http.NewRequest("GET", "http://blank.org", nil)
    
               // Propagate the trace header info in the outgoing requests.
               r = r.WithContext(req.Context())
               resp, err := client.Do(r)
    
               if err != nil {
                   log.Println(err)
               } else {
                   // TODO: handle response
                   resp.Body.Close()
               }        
           })
    
           log.Fatal(http.ListenAndServe(":50030", &ochttp.Handler{Propagation: &tracecontext.HTTPFormat{}}))
    
       }
    
  3. 运行 Simple Go 应用后,导航到 http://localhost:50030Once the simple go app is running navigate to http://localhost:50030. 每次刷新浏览器都将生成文本“hello world”,并附带由本地转发器拾取的相应 span 数据。Each refresh of the browser will generate the text "hello world" accompanied by corresponding span data that is picked up by the local forwarder.

  4. 若要确认本地转发器是否正在拾取跟踪,请检查 LocalForwarder.config 文件。To confirm that the local forwarder is picking up the traces check the LocalForwarder.config file. 如果已按照先决条件中的步骤执行了操作,它将位于 C:\LF-WindowsServiceHost 中。If you followed the steps in the prerequisite, it will be located in C:\LF-WindowsServiceHost.

    在下面的日志文件图像中,可以看到在运行第二个脚本(已在其中添加了导出程序)之前,OpenCensus input BatchesReceived 为 0。In the image below of the log file, you can see that prior to running the second script where we added an exporter OpenCensus input BatchesReceived was 0. 开始运行更新的脚本以后,BatchesReceived 根据我们输入的值的数目递增:Once we started running the updated script BatchesReceived incremented equal to the number of values we entered:

    “新建 App Insights 资源”窗体

开始在 Azure 门户中监视Start monitoring in the Azure portal

  1. 现在可以在 Azure 门户中重新打开 Application Insights“概览” 页,查看当前正在运行的应用程序的详细信息。You can now reopen the Application Insights Overview page in the Azure portal, to view details about your currently running application. 选择“实时指标流” 。Select Live Metric Stream.

    概览窗格的屏幕截图,其中的实时指标流在红框中呈选中状态。

  2. 如果再次运行第二个 Go 应用并针对 http://localhost:50030 开始刷新浏览器,则当实时跟踪数据从本地转发器服务到达 Application Insights 时,你会看到它们。If you run the second Go app again and start refreshing the browser for http://localhost:50030, you will see live trace data as it arrives in Application Insights from the local forwarder service.

    实时指标流的屏幕截图,其中显示了性能数据

  3. 导航回“概览”页,选择“应用程序映射”以获取应用程序组件之间依赖关系和调用时间的可视布局。 Navigate back to the Overview page and select Application Map for a visual layout of the dependency relationships and call timing between your application components.

    基本应用程序映射的屏幕截图

    由于我们只跟踪一个方法调用,因此应用程序映射的信息不多。Since we were only tracing one method call, our application map isn't as interesting. 但是,应用程序映射可以通过缩放将多得多的分布式应用程序可视化:But application map can scale to visualize far more distributed applications:

    应用程序地图

  4. 选择“调查性能”,执行详细的性能分析并确定性能减慢的根本原因。 Select Investigate Performance to perform detailed performance analysis and determine the root cause of slow performance.

    性能窗格的屏幕截图

  5. 选择“示例”,然后单击显示在右窗格中的任意示例,这将启动端到端事务详细信息体验。 Selecting Samples and then clicking on any of the samples that appear in the right-hand pane will launch the end-to-end transaction details experience. 虽然我们的示例应用只会显示单个事件,但更复杂的应用程序会让你在探索端到端事务时,可以深入到单个事件的调用堆栈级别。While our sample app will just show us a single event, a more complex application would allow you to explore the end-to-end transaction down to level of an individual event's call stack.

    端到端事务界面的屏幕截图

适用于 Go 的 OpenCensus 跟踪OpenCensus trace for Go

我们只简单介绍了如何将适用于 Go 的 OpenCensus 与本地转发器和 Application Insights 集成。We only covered the basics of integrating OpenCensus for Go with the local forwarder and Application Insights. 官方 OpenCensus Go 使用指南介绍更高级的主题。The official OpenCensus Go usage guidance covers more advanced topics.

后续步骤Next steps