通过观测云 DataKit Extension 接入 AWS Lambda 最佳实践

前言

AWS Lambda 是一项计算服务,使用时无需预配置或管理服务器即可运行代码。AWS Lambda 只在需要时执行代码并自动缩放。借助 AWS Lambda,几乎可以为任何类型的应用程序或后端服务运行代码,而且无需执行任何管理。

Lambda Layer 是一个包含补充代码或数据的 .zip 文件存档,通常包含库依赖项、自定义运行时系统或配置文件。Lambda 扩展则是可以增强 Lambda 函数的功能,例如集成监控、安全性和监管工具等。

在本文中,我们将引导您了解如何将观测云服务集成到 AWS Lambda,通过配置 Lambda 层、设置环境变量,实现 Lambda 函数的指标、日志和链路采集。

前提条件

  • 确保您拥有 AWS 账户,并且具备管理 Lambda 函数的权限。
  • 已注册观测云账号

第1步:创建Lambda层

1、打开 AWS Lambda 控制台并导航至「Layers」页面。

2、点击「Create layer」,创建一个新的层。

3、在「Layer configuration」中,填写层的名称。

4、选择「Upload a .zip file」并上传以下链接对应的文件:

第2步:复制 ARN 并添加层到 Lambda 函数

  • 创建成功后,复制层的 ARN 值。
  • 在 Lambda 函数配置中添加此 ARN 到 Layers 部分。

第3步:配置环境变量

设置以下环境变量以确保数据正确传输到观测云:

Datakit 监听的地址名

  • DD_AGENT_HOST: 0.0.0.0

Datakit 监听的端口号

  • DD_TRACE_AGENT_PORT: 9529

DataWay 真实地址

  • ENV_DATAWAY: https://xxxx.guance.com?token=<your-token>

第4步:日志、链路和指标采集

日志采集

  • 支持采集控制台日志。
  • Node.js 18.x 和 Go 日志采集示例。

链路采集

  • 使用 OpenTelemetry 或 DDTrace 进行链路采集

  • 对于 Go 语言,需要在业务代码中添加相应的追踪代码。Go 代码示例较为复杂,需要修改业务代码,示例如下:

    package main

    import (
    "context"
    "fmt"
    "github.com/aws/aws-lambda-go/lambda"
    "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
    "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
    "os"
    "time"
    )

    type MyEvent struct {
    Name string json:"name"
    }

    func HandleRequest(ctx context.Context, event *MyEvent) (*string, error) {
    return run(ctx, event)
    }

    func run(ctx context.Context, event *MyEvent) (*string, error) {
    tracer.Start(
    tracer.WithEnv("prod"),
    tracer.WithService("test-file-read"),
    tracer.WithServiceVersion("1.2.3"),
    tracer.WithGlobalTag("project", "add-ddtrace-in-golang-project"),
    tracer.WithLambdaMode(false),
    )

    复制代码
          // end of app exit, make sure tracer stopped
          defer tracer.Stop()
    
          tick := time.NewTicker(time.Second)
          defer tick.Stop()
          ctx, cancel := context.WithTimeout(ctx, time.Minute*2)
          defer cancel()
          // your-app-main-entry...
          for {
                  runApp()
                  runAppWithError()
    
                  select {
                  case <-tick.C:
                  case <-ctx.Done():
                          message := fmt.Sprintf("Hello %s!", event)
                          return &message, nil
                  }
          }

    }

    func main() {
    //run(context.Background(), &MyEvent{Name: "Hello World!"})
    lambda.Start(HandleRequest)
    }

    func runApp() {
    var err error
    // Start a root span.
    span := tracer.StartSpan("get.data")
    defer span.Finish(tracer.WithError(err))

    复制代码
          // Create a child of it, computing the time needed to read a file.
          child := tracer.StartSpan("read.file", tracer.ChildOf(span.Context()))
          child.SetTag(ext.ResourceName, os.Args[0])
    
          // Perform an operation.
          var bts []byte
          bts, err = os.ReadFile(os.Args[0])
          span.SetTag("file_len", len(bts))
          child.Finish(tracer.WithError(err))

    }

    func runAppWithError() {
    var err error
    // Start a root span.
    span := tracer.StartSpan("get.data")

    复制代码
          // Create a child of it, computing the time needed to read a file.
          child := tracer.StartSpan("read.file", tracer.ChildOf(span.Context()))
          child.SetTag(ext.ResourceName, "somefile-not-found.go")
    
          defer func() {
                  child.Finish(tracer.WithError(err))
                  span.Finish(tracer.WithError(err))
          }()
    
          // Perform an error operation.
          if _, err = os.ReadFile("somefile-not-found.go"); err != nil {
                  // error handle
          }

    }

  • 链路效果展示

指标采集

以下是 AWS Lambda 指标的详细列表

awslambda-metric

标签 描述
aws_account_id AWS 账户ID。
aws_lambda_function_memory_size Configured memory size for the Lambda function.
aws_lambda_function_name Lambda function name.
aws_lambda_function_version Lambda function version.
aws_lambda_initialization_type Initialization type of the Lambda function.
aws_region AWS region where the function is executed.
指标 描述 类型 单位
billed_duration_ms Billed duration in milliseconds. int ms
duration_ms Total duration in milliseconds. int ms
errors Errors count. int count
init_duration_ms Initialization duration in milliseconds. int ms
invocations Invocation count. int count
max_memory_used_mb Maximum memory used in MB. int Mb
memory_size_mb Memory size configured for the Lambda function in MB. int Mb
out_of_memory Out of memory errors count. int count
post_runtime_duration Duration of the post-runtime phase in milliseconds. int ms
produced_bytes Bytes produced. int B
response_duration_ms Response duration in milliseconds. int ms
response_latency Response latency in milliseconds. int ms
runtime_duration_ms Duration of the runtime in milliseconds. int ms
timeouts Timeouts count. int count

安全和隐私说明

  • 确保在配置 ENV_DATAWAY 时使用安全的连接(例如 HTTPS)。
  • 不要在日志或错误消息中暴露敏感信息。

注意事项

  • 在部署之前,确保测试所有配置。
  • 监控Lambda函数的性能,确保指标收集符合预期。
  • 定期检查Lambda层和相关配置是否有更新。

参考资料

相关推荐
猫头虎-前端技术7 小时前
JS 作用域与闭包:从变量提升到闭包陷阱的超详细解析
开发语言·javascript·云计算·bootstrap·ecmascript·openstack·perl
hwscom11 小时前
腾讯云如何在安全组开放端口
安全·云计算·腾讯云
翼龙云_cloud14 小时前
腾讯云代理商:腾讯云云桌面如何部署Hermes Agent?
人工智能·云计算·腾讯云·ai智能体·hermes agent
Cloud_Shy61815 小时前
Linux 系统定时任务 Cron(d) 服务应用实践(二:生产环境下的用户定时任务)
linux·运维·服务器·centos·云计算
weixin_4684668516 小时前
大语言模型快速部署与调用指南
人工智能·ai·自然语言处理·大模型·云计算·大语言模型·本地化部署
xixixi7777717 小时前
Token 经济重构价值分配:中国移动成核心枢纽,算网安一体化按需计费普惠中小企业
人工智能·ai·大模型·云计算·算力·token·流量
搞科研的小刘选手19 小时前
【南昌大学主办】第五届人工智能、物联网和云计算技术国际会议(AIoTC 2026)
人工智能·物联网·网络安全·大模型·云计算·智慧城市·云安全
运维行者_19 小时前
使用Applications Manager监控的关键MongoDB指标
服务器·开发语言·网络·数据库·mongodb·机器学习·云计算
app开发工程师V帅19 小时前
OpenClaw 配置教程:云端部署(腾讯云)和本地部署
云计算·腾讯云
河北小博博21 小时前
从理解到落地:AI Agent 长期记忆系统的原理、框架与阿里云选型指南
人工智能·阿里云·云计算