登录
首页 >  Golang >  Go问答

Golang 分析包带有文本输出功能

来源:stackoverflow

时间:2024-02-29 23:39:16 279浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《Golang 分析包带有文本输出功能》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我有一个在 AWS Fargate 上运行的微服务,即作为 docker 容器,一小时后开始变慢,但内存使用量保持不变。当前从计算机中获取数据的唯一简单方法是将其写入 Amazon S3 或 stdout。

我的问题:是否有一个包可以以某种方式对分析信息进行采样,然后我可以将其打印到标准输出?


正确答案


您可以每 15 分钟创建一个堆和 cpu 配置文件,并使用有权上传到您的存储桶的实例配置文件将其上传到 s3。

func startCpuProfile() {
    cpuProfile, err := os.Create("cpu_profile")
    if err != nil {
        log.Println("could not create CPU profile: ", err)
    }
    defer cpuProfile.Close()

    if err := pprof.StartCPUProfile(cpuProfile); err != nil {
        log.Println("could not start CPU profile: ", err)
    }
}

func generateProfileBundle() {
    ts := time.Now().Format("2006-01-02_15:04:05")
    heapProfile, err := os.Create("heap_profile_" + ts)
    if err != nil {
        log.Println("could not create memory profile: ", err)
    }
    defer heapProfile.Close()

    runtime.GC()
    if err := pprof.WriteHeapProfile(heapProfile); err != nil {
        log.Println("could not write memory profile: ", err)
    }

    pprof.StopCPUProfile()

    svc := s3.New(session.New())

    cpuFile, err := os.Open("cpu_profile")

    _, err = svc.PutObject(&s3.PutObjectInput{
        Bucket: aws.String("service_profile_bucket"),
        Key:    aws.String("cpu_profile_" + ts),
        Body:   cpuFile,
    })


    _, err = svc.PutObject(&s3.PutObjectInput{
        Bucket: aws.String("service_profile_bucket"),
        Key:    aws.String("heap_profile_" + ts),
        Body:   heapProfile,
    })

    os.Remove("cpu_profile")
    os.Remove("heap_profile_" + ts)

    startCpuProfile()
}

func main() {
    // Start CPU Profile at start up
    startCpuProfile()
    // Every 15 minutes dump a heap profile, restart the CPU profile and upload to S3
    ticker := time.Tick(time.Minute * 15)
    go func() {
        for _ = range ticker {
            generateProfileBundle()
        }
    }()
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>